有效的括号
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
题解
bool isValid(string s) {
stack<char> c;
if(s=="") return true;
for(int i=0;i<s.length();i++){
switch(s[i]){
case '(':c.push(s[i]);break;
case '[':c.push(s[i]);break;
case '{':c.push(s[i]);break;
case ')':
if(!c.empty()&&c.top()=='(')
c.pop();
else return false;
break;
case ']':
if(!c.empty()&&c.top()=='[')
c.pop();
else return false;
break;
case '}':
if(!c.empty()&&c.top()=='{')
c.pop();
else return false;
break;
}
}
return c.empty()?true:false;
}
注意
需要加上栈不为空的 判断条件 否则报错AddressSanitizer:DEADLYSIGNAL
if(!c.empty()&&c.top()=='(')
if(!c.empty()&&c.top()=='[')
if(!c.empty()&&c.top()=='{')