-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_20_valid_parentheses.java
More file actions
35 lines (32 loc) · 1013 Bytes
/
Copy path_20_valid_parentheses.java
File metadata and controls
35 lines (32 loc) · 1013 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
28
29
30
31
32
33
34
35
import java.util.Stack;
public class _20_valid_parentheses {
public static boolean isValid(String s) {
Stack<Character> myStack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(' || c == '{' || c == '[') {
myStack.push(c);
} else {
if (myStack.isEmpty()) {
return false;
}
char top = myStack.peek();
if ( (c==')' && top == '(')
|| (c==']' && top == '[')
|| (c=='}' && top == '{') ) {
myStack.pop();
} else {
return false;
}
}
}
return myStack.isEmpty();
}
public static void main(String[] args) {
// String s = "()[]{}";
// String s = "(]";
String s = "{[]}";
// String s = "([)]";
System.out.println(isValid(s));
}
}