Includes only a given '('
, ')'
, '{'
, '}'
, '['
, ']'
string, determines whether the string is valid.
A valid string must meet:
- The left parenthesis must be closed with the same type of right parenthesis.
- The opening parenthesis must be closed in the correct order.
Note that an empty string can be considered a valid string.
Example 1:
Input: “()”
Output: true
Example 2:
Input: “()[]{}”
Output: true
Example 3:
Input: “(]”
Output: false
Example 4:
Input: “([)] "
Output: false
Example 5:
Input: "{[]}"
Output: true
public boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<>();//一种数据结构
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[') {
stack.push(s.charAt(i));
} else {
if (stack.isEmpty()) {
return false;
} else {
if (stack.peek() == '(' && s.charAt(i) != ')') {
return false;//返回栈顶元素
} else if (stack.peek() == '{' && s.charAt(i) != '}') {
return false;
} else if (stack.peek() == '[' && s.charAt(i) != ']') {
return false;
}
stack.pop();
}
}
}
return stack.isEmpty();
}