-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathValidParentheses.java
More file actions
executable file
·33 lines (27 loc) · 918 Bytes
/
ValidParentheses.java
File metadata and controls
executable file
·33 lines (27 loc) · 918 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
import java.util.Stack;
/**
* Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
* determine if the input string is valid.
* The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
* <p>
* Accepted.
*/
public class ValidParentheses {
public boolean isValid(String s) {
if (s == null || s.length() == 0 || s.length() == 1) {
return false;
}
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (!stack.isEmpty() && (c == ')' && stack.peek() == '('
|| c == ']' && stack.peek() == '['
|| c == '}' && stack.peek() == '{')) {
stack.pop();
} else {
stack.push(c);
}
}
// System.out.println(stack);
return stack.isEmpty();
}
}