题解 | #合法的括号字符串#

合法的括号字符串

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

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return bool布尔型
     */

    bool isValidString(string s) {
        // write code here
        stack<int> sta_left;
        stack<int> sta_star;
        if(s.size()<2 || s[0] == ')' || s[s.size()-1] == '('){
            return false;
        }
        for(int i=0;i<s.size();i++){
            if(s[i] == '('){
                sta_left.push(i);
            }else if(s[i] == '*'){
                sta_star.push(i);
            }else if(s[i] == ')'){
                if(sta_left.size()){
                    sta_left.pop();
                }else if(sta_star.size()){
                    sta_star.pop();
                }else{
                    return false;
                }
            }
        } 
        while(sta_left.size()){
            if(sta_star.size()==0){
                return false;
            }else{
                if(sta_left.top()<sta_star.top()){
                        sta_left.pop();
                        sta_star.pop();
                }else{
                    return false;
                }
            }
        }
        
        return true;
    }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务