Given a string 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.
Note that an empty string is also considered valid.
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
题目:括号匹配,按照数学里的括号匹配规则即可。
思路:括号匹配问题是数据结构中栈必学习的内容,对于string s,如果是左括号,则入栈,如果是右括号,查看是否与栈顶成对,不成对则return false,成对则将栈顶元素出栈。遍历完s之后检查栈是否为空,不为空返回false,否则返回true。
代码:
class Solution {
public:
bool isValid(string s) {
stack<char> stack;
int size = s.size();
for(int i=0;i<size;i++){
if(s[i]==')'||s[i]=='}'||s[i]==']'){
if(stack.empty())
return false;
if(s[i]==')'){
if(stack.top()!='(')
return false;
else
stack.pop();
}
if(s[i]==']'){
if(stack.top()!='[')
return false;
else
stack.pop();
}
if(s[i]=='}'){
if(stack.top()!='{')
return false;
else
stack.pop();
}
}
else
stack.push(s[i]);
}
if(stack.empty())
return true;
else
return false;
}
};
AC beats100%。