Description
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) {
int len = s.size();
if(len == 0) return false;
stack<char> Stack;
for(int i = 0; i < len; ++i){
if(s[i] == '(' || s[i] == '{' || s[i] == '[')
Stack.push(s[i]);
else if(s[i] == ')'){
if(Stack.empty() || Stack.top() != '(')
return false;
else Stack.pop();
}
else if(s[i] == '}'){
if(Stack.empty() || Stack.top() != '{')
return false;
else Stack.pop();
}
else if(s[i] == ']'){
if(Stack.empty() || Stack.top() != '[')
return false;
else Stack.pop();
}
else return false;
}
return Stack.empty();
}
};