Skip to content

Commit 96f433c

Browse files
committed
Solution: Valid Parentheses
1 parent 486d50b commit 96f433c

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* ํ’€์ด
3+
* - stack ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์ด์šฉํ•ฉ๋‹ˆ๋‹ค
4+
*
5+
* Big O
6+
* - N: ์ฃผ์–ด์ง„ ๋ฌธ์ž์—ด s์˜ ๊ธธ์ด
7+
*
8+
* - Time complexity: O(N)
9+
* - ๋ฌธ์ž์—ด s ์ „์ฒด๋ฅผ ์ˆœํšŒํ•  ๊ฒฝ์šฐ ์‹คํ–‰์‹œ๊ฐ„์€ N์— ์„ ํ˜•์ ์œผ๋กœ ๋น„๋ก€ํ•˜์—ฌ ์ฆ๊ฐ€ํ•ฉ๋‹ˆ๋‹ค
10+
* - Space complexity: O(N)
11+
* - "((((((...((((((" ์™€ ๊ฐ™์€ ์ž…๋ ฅ์„ ๋ฐ›์œผ๋ฉด stack์˜ ํฌ๊ธฐ๊ฐ€ ์ตœ๋Œ€ N๊นŒ์ง€ ์ฆ๊ฐ€ํ•ฉ๋‹ˆ๋‹ค
12+
*/
13+
14+
class Solution {
15+
public:
16+
bool isValid(string s) {
17+
stack<char> st;
18+
for (char ch : s) {
19+
if (ch == '(' || ch == '{' || ch == '[') {
20+
st.push(ch);
21+
} else {
22+
if (st.empty()) return false;
23+
else if (st.top() == '(' && ch == ')') st.pop();
24+
else if (st.top() == '{' && ch == '}') st.pop();
25+
else if (st.top() == '[' && ch == ']') st.pop();
26+
else return false;
27+
}
28+
}
29+
return st.empty();
30+
}
31+
};

0 commit comments

Comments
ย (0)