-
Notifications
You must be signed in to change notification settings - Fork 0
/
ValidParentheses.java
51 lines (38 loc) · 1.32 KB
/
ValidParentheses.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
* Key point: using stack
*
* I made attempts on using dfs. not a good idea
*/
public class Solution {
public boolean isValid(String s) {
if(s == null || s == "")
return true;
if(s.length() % 2 == 1)
return false;
Stack<Character> st = new Stack<Character>();
for(int i = 0;i<s.length();i++){
char current = s.charAt(i);
//left parts are always pushed to stack
if(current == '(' || current == '[' || current == '{')
st.push(current);
//as soon as meeting a right part, pop() an element
//if didn't match, return false
if(current == ')'){
if(st.empty() || st.pop() != '(')
return false;
}
if(current == ']'){
if(st.empty() || st.pop() != '[')
return false;
}
if(current == '}'){
if(st.empty() || st.pop() != '{')
return false;
}
}
//if the stack isn't empty after scanning the whole string
if(st.empty() == false)
return false;
return true;
}
}