-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
31 lines (26 loc) · 990 Bytes
/
Solution.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
import java.util.Stack;
class Solution {
public boolean isValid(String s) {
if (s.length() == 1) return false;
Stack<Character> openingChars = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(' || c == '{' || c == '[') {
openingChars.push(c);
continue;
}
if (openingChars.isEmpty()) return false;
if (c == ')' && openingChars.pop() != '(') return false;
if (c == '}' && openingChars.pop() != '{') return false;
if (c == ']' && openingChars.pop() != '[') return false;
}
return openingChars.isEmpty();
}
public static void main(String args[]) {
Solution s = new Solution();
System.out.println(s.isValid("()"));
System.out.println(s.isValid("()[]{}"));
System.out.println(s.isValid("(]"));
System.out.println(s.isValid("([]"));
System.out.println(s.isValid("}["));
}
}