题目:有效的括号
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
1.左括号必须用相同类型的右括号闭合。
2.左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
代码:
class Solution {
public:
bool isValid(string s) {
stack<char> str;
int len = s.length();
for(int i=0;i<len;i++)
{
char c=s[i];
if(c=='('||c=='{'||c=='[') str.push(c);
else{
if(str.empty()) return false;
char c_top = str.top();
if(c_top=='('&&c!=')') return false;
if(c_top=='['&&c!=']') return false;
if(c_top=='{'&&c!='}') return false;
str.pop();
}
}
return str.empty();
}
};