https://leetcode.com/problems/valid-parentheses/description/
题目:判断某个字符序列是否合法
思路:如果是左括号,直接压栈,如果是右括号,如果栈顶元素不匹配当前元素或者栈为空,return 0,否则弹出元素。最后判断是否为空。
class Solution {
public:
bool isValid(string s) {
int len=0;
stack<char>temp;
while(s[len]!='\0')
{
if(s[len]=='('||s[len]=='['||s[len]=='{') temp.push(s[len]);
else if(s[len]==')')
{
if(temp.empty()||temp.top()!='(') return 0;
temp.pop();
}
else if(s[len]==']')
{
if(temp.empty()||temp.top()!='[') return 0;
temp.pop();
}
else if(s[len]=='}')
{
if(temp.empty()||temp.top()!='{') return 0;
temp.pop();
}
len++;
}
return temp.empty();
}
};