【Leetcode】
问题描述
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> r;
if(s.length()<1)
return true;
r.push(s[0]);
for(int i=1;i<s.length();i++) {
if(r.size()>0&&(s[i]==')'&&r.top()=='('
|| s[i]==']'&&r.top()=='['
|| s[i]=='}'&&r.top()=='{')) {
r.pop();
} else {
r.push(s[i]);
}
}
if(r.size()>0)
return false;
return true;
}
};