您的位置:首页 > 其它

20. Valid Parentheses LeetCode

2016-02-12 13:02 429 查看
题意:给出一个只包括3种括号的字符串,问这个字符串中的括号排列是否合法。

题解:用stack来模拟一遍。最后判断stack是否为空就知道合不合法。

class Solution {
public:
bool isValid(string s) {
int n = s.length();
stack<int> sta;
while(!sta.empty()) sta.pop();
for(int i = 0; i < n; i++)
{
if(sta.empty()) sta.push(i);
else
{
if((s[sta.top()] == '(' && s[i] == ')') || (s[sta.top()] == '[' && s[i] == ']') || (s[sta.top()] == '{' && s[i] == '}'))
sta.pop();
else sta.push(i);
}
}
if(!sta.empty()) return false;
else return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode