File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
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
+
You can’t perform that action at this time.
0 commit comments