题解 | #合法的括号字符串#单调栈模拟,简单易懂

合法的括号字符串

https://www.nowcoder.com/practice/eceb50e041ec40bd93240b8b3b62d221

#include <stack>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return bool布尔型
     */
    bool isValidString(string s) {
        stack<char>left;
        stack<char>star;
        stack<int>lefti;
        stack<int>stari;
        for(int i = 0;i<s.size();i++)
        {
            if(s[i]=='(')
            {
                left.push(s[i]);
                lefti.push(i);
            }
            else if(s[i]=='*')
            {
                star.push(s[i]);
                stari.push(i);
            }
            else if(s[i]==')')
            {
                if(!left.empty())
                {
                    left.pop();
                    lefti.pop();
                }
                else if(!star.empty())
                {
                    star.pop();
                    stari.pop();
                }
                else if(star.empty()&&left.empty())return false;
            }
        }
        while(!left.empty())
        {
            if(!star.empty()&&stari.top()>lefti.top())//*在(的后面
            {
                star.pop();
                left.pop();
                stari.pop();
                lefti.pop();
            }    
            else return false;
        }
        return true;
    }
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务