-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path20. Valid Parentheses
75 lines (65 loc) · 1.72 KB
/
20. Valid Parentheses
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
class Solution {
Map<Character, Character> map;
public boolean isValid(String s) {
map = new HashMap<>();
map.put(')', '(');
map.put(']', '[');
map.put('}', '{');
Stack<Character> st=new Stack<>();
for(int i=0;i<s.length();i++) {
char c = s.charAt(i);
if(map.containsValue(c)) {
st.push(c);
} else {
if(st.isEmpty() || map.get(c) != st.pop()) {
return false;
}
}
}
return st.isEmpty();
}
}
class Solution {
Map<Character,Character> map=new HashMap<>();
public boolean isValid(String s) {
map.put('}','{');
map.put(')','(');
map.put(']','[');
//Stack<Character> st=new Stack<>();
int top=-1;
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
if(map.containsValue(c)){
//st.push(c);
top=i;
}
else{
if(top==-1 || map.get(c)!=s.charAt(top)){
return false;
}
else{
top=getTop(s,top-1);
}
}
}
return top==-1;
}
int getTop(String s,int index){
int right=0;
while(index>=0){
char ch=s.charAt(index);
if(map.containsKey(ch))// ch = is closing bracket
{
right++;
}
else{
right--;
}
if(right<0){
return index;
}
index--;
}
return -1;
}
}