Skip to content

Commit b43d556

Browse files
committed
valid parentheses
1 parent 70c9b19 commit b43d556

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+
* Runtime: 4ms
3+
* Time Complexity: O(n)
4+
*
5+
* Memory: 42.94MB
6+
* Space Complexity: O(n)
7+
*
8+
* Approach: ์Šคํƒ ์‚ฌ์šฉ
9+
* - ์—ด๋ฆฐ ๊ด„ํ˜ธ๋ฅผ ํ‘ธ์‹œํ•˜๋ฉด์„œ ๋‹ซํžŒ ๊ด„ํ˜ธ๊ฐ€ ๋‚˜์˜ฌ ๋•Œ๋งˆ๋‹ค ์Šคํƒ์—์„œ ํŒํ•˜์—ฌ ์ง์ด ๋งž๋Š”์ง€ ํ™•์ธ
10+
*/
11+
class Solution {
12+
public boolean isValid(String s) {
13+
if (s.length()%2 == 1) return false;
14+
15+
Stack<Character> stack = new Stack<>();
16+
Map<Character, Character> map = new HashMap<>();
17+
map.put('(', ')');
18+
map.put('{', '}');
19+
map.put('[', ']');
20+
21+
for (char ch: s.toCharArray()) {
22+
if (map.containsKey(ch)) {
23+
stack.push(ch);
24+
} else if (")}]".indexOf(ch) != -1) {
25+
if (stack.isEmpty() || ch != map.get(stack.pop())) {
26+
return false;
27+
}
28+
}
29+
}
30+
31+
return stack.isEmpty();
32+
}
33+
}

0 commit comments

Comments
ย (0)