Skip to content

Commit 5460104

Browse files
committed
Valid Parentheses
1 parent 222ba96 commit 5460104

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
Time Complexity: O(n)
3+
Space Complexity: O(n)
4+
5+
์œ ํšจํ•œ ๋ฌธ์ž์—ด์ด๋ผ๋ฉด, ์ธ์ ‘ํ•œ ์—ด๊ณ  ๋‹ซ๋Š” ๊ด„ํ˜ธ ์Œ์„ ํ•˜๋‚˜์”ฉ ์บ”์Šฌ์‹œ์ผฐ์„ ๋•Œ, ๋นˆ ๋ฌธ์ž์—ด๋งŒ ๋‚จ๊ฒŒ ๋œ๋‹ค.
6+
๋งค์น˜๋˜๋Š” ์Œ์ด ์„œ๋กœ ๋–จ์–ด์ ธ์žˆ์„ ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์—, ๊ทธ ์•ˆ์˜ ์œ ํšจํ•œ ์Œ๋“ค์„ ๋ฏธ๋ฆฌ ๋ชจ๋‘ ์บ”์Šฌ์‹œํ‚จ ๋’ค์— ํŒ๋‹จํ•ด์•ผ ๋งค์นญ ์—ฌ๋ถ€๋ฅผ ์‰ฝ๊ฒŒ ํŒ๋‹จํ•  ์ˆ˜ ์žˆ๋Š”๋ฐ, ์ด ๊ณผ์ •์„ ์Šคํƒ์„ ์ด์šฉํ•ด ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋‹ค.
7+
*/
8+
class Solution {
9+
public boolean isValid(String s) {
10+
Stack<Character> st = new Stack<>();
11+
12+
for (char ch : s.toCharArray()) {
13+
if (ch == '(' || ch == '{' || ch == '[') {
14+
st.push(ch);
15+
} else {
16+
if (st.empty())
17+
return false;
18+
if (ch == ')') {
19+
if (st.peek() != '(')
20+
return false;
21+
} else if (ch == '}') {
22+
if (st.peek() != '{')
23+
return false;
24+
} else {
25+
if (st.peek() != '[')
26+
return false;
27+
}
28+
st.pop();
29+
}
30+
}
31+
return st.empty();
32+
}
33+
}

0 commit comments

Comments
ย (0)