20. Valid Parentheses LeetCode

来源:互联网 发布:matlab混合编程 编辑:程序博客网 时间:2024/04/29 15:37

题意:给出一个只包括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;    }};
0 0