-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalid-parentheses.java
34 lines (32 loc) Β· 976 Bytes
/
valid-parentheses.java
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
28
29
30
31
32
33
34
import java.util.Stack;
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
HashMap<Character, Character> hm = new HashMap<>();
hm.put('}', '{');
hm.put(']', '[');
hm.put(')', '(');
// iterate over string and push to stack
int i = 0;
while(i < s.length()){
if(s.charAt(i) == (char) '}' || s.charAt(i) == ']' || s.charAt(i) == ')'){
if(stack.empty()){return false;}
System.out.println(hm.get(s.charAt(i)));
if(stack.peek() == hm.get(s.charAt(i))){
stack.pop();
}
else {
return false;
}
}
else{
stack.push(s.charAt(i));
}
i++;
}
if(stack.size() == 0){
return true;
}
return false;
}
}