Skip to content

Commit 4a85208

Browse files
committed
- valid parentheses 풀이 추가
1 parent 668e45f commit 4a85208

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

valid-parentheses/Geegong.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import java.util.HashMap;
2+
import java.util.Stack;
3+
4+
public class Geegong {
5+
6+
/**
7+
* stack 자료구조 사용
8+
* 닫는 부분만 hashMap의 key 값으로 서로 페어가 되는 값을 value 로 한다.
9+
* stack 자료구조는 닫는 bracket이 아니면 push 해서 넣고 닫는 bracket 만 체크를 하는데
10+
* stack 에서 pop 을 하는데 이떄 map의 value와 다르면 false
11+
*
12+
* time complexity : o(n)
13+
* space complexity : o(1)
14+
* @param s
15+
* @return
16+
*/
17+
public boolean isValid(String s) {
18+
HashMap<Character, Character> map = new HashMap<Character, Character>();
19+
map.put(')', '(');
20+
map.put(']', '[');
21+
map.put('}', '{');
22+
23+
Stack<Character> stack = new Stack<Character>();
24+
for (int i=0; i<s.length(); i++) {
25+
Character ch = s.charAt(i);
26+
if (map.containsKey(ch)) {
27+
if (stack.isEmpty() || map.get(ch) != stack.pop()) {
28+
return false;
29+
}
30+
} else {
31+
stack.push(ch);
32+
}
33+
}
34+
35+
return stack.isEmpty();
36+
}
37+
}
38+

0 commit comments

Comments
 (0)