20. Valid Parentheses
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.
题解
判断括号是否匹配。
class Solution {
public:
bool isValid(string s) {
stack<char> S;
for(int i = 0; i < s.length(); ++i){
if(s[i] == '(' || s[i] == '[' || s[i] == '{') S.push(s[i]);
else{
if(S.empty()) return false;
char top = S.top(); S.pop();
if(s[i] == ')' && top != '(') return false;
if(s[i] == ']' && top != '[') return false;
if(s[i] == '}' && top != '{') return false;
}
}
return S.empty();
}
};
public class Solution {
public boolean isValid(String s) {
Stack<Integer> p = new Stack<>();
for(int i = 0; i < s.length(); i++) {
int q = "(){}[]".indexOf(s.substring(i, i + 1));
if(q % 2 == 1) {
if(p.isEmpty() || p.pop() != q - 1) return false;
} else p.push(q);
}
return p.isEmpty();
}
}