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.
exa:
"(){}[]" true:
"{[()]}" true
"(}{}[]" false
按照括号规则必须首先出现‘(’或者‘{’,‘[’否则肯定不是合理括号组合,当‘(’或者‘{’,‘[’将对应的右括号')','}',']'入栈然后判断字符串下一个字符非‘(’或者‘{’,‘[’时是否等于刚刚入栈的字符即可:
class Solution {
private:
stack<char>ss;
public:
bool isValid(string s) {
int l=s.length();
if(l%2!=0||l==0)return false;
int i;
for(i=0;i<l;i++)
{if(s[i]=='(')ss.push(')');
else if(s[i]=='[')ss.push(']');
else if(s[i]=='{')ss.push('}');
else if((ss.empty()==true)||(ss.top()!=s[i])){return 0;}//先判断空,只有非空情况下再看ss.top,不能先看ss.top再判断空
else ss.pop();}
if(ss.empty())return 1;
else return 0;
}
};