-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path20-validcir.java
More file actions
27 lines (26 loc) · 881 Bytes
/
20-validcir.java
File metadata and controls
27 lines (26 loc) · 881 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.*;
class Solution_20 {
public boolean isValid(String s) {
if(s.length()==0) return true;
if(s.length()%2!=0) return false;
Stack<Character> stack = new Stack<Character>();
HashMap<Character, Character> map = new HashMap<Character, Character>();
map.put('(', ')');
map.put('{', '}');
map.put('[', ']');
for(int i=0; i< s.length(); i++) {
// System.out.println(map.get(s.charAt(i)));
if(!map.containsKey(s.charAt(i))) {
if(!stack.empty() && stack.pop() == s.charAt(i)) {
map.remove(s.charAt(i));
} else {
return false;
}
} else {
stack.push(map.get(s.charAt(i)));
}
}
if(!stack.empty()) return false;
return true;
}
}