Valid Parentheses
Given a string s
containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Example 1:
Input: s = "()" Output: true
Example 2:
Input: s = "()[]{}" Output: true
Example 3:
Input: s = "(]" Output: false
Example 4:
Input: s = "([)]" Output: false
Example 5:
Input: s = "{[]}" Output: true
class Solution {
public boolean isValid(String s) {
//扫描到左括号就压栈,扫描到右括号就弹栈,如果不匹配,返回false
//如果扫描结束后,栈内还有东西,返回false
//结束后栈空了,返回true
//扫描到右括号时,栈空,返回false
Stack<Character> res = new Stack<>();
char[] str = s.toCharArray();
for (int i = 0; i < str.length; i++) {
if (str[i] == '(' || str[i] == '[' || str[i] == '{') {
res.push(str[i]);
}
if (str[i] == ')') {
if (res.isEmpty()) {
return false;
}
char c = res.pop();
if (c != '('){
return false;
}
}
if (str[i] == ']') {
if (res.isEmpty()) {
return false;
}
char c = res.pop();
if (c != '['){
return false;
}
}
if (str[i] == '}') {
if (res.isEmpty()) {
return false;
}
char c = res.pop();
if (c != '{'){
return false;
}
}
}//扫描结束
if (!res.isEmpty()) {
return false;
}
return true;
}
}