题解 | #有效括号序列#

有效括号序列

http://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2

public:
    /**
     * 
     * @param s string字符串 
     * @return bool布尔型
     */
    bool sign(int i,stack<char> &chars,string str){
        if(chars.top()=='('&&str[i]==')'){
            return true;
        }
        if(chars.top()=='['&&str[i]==']'){
            return true;
        }
        if(chars.top()=='{'&&str[i]=='}'){
            return true;
        }
        return false;
    }
    bool isValid(string s) {
        // write code here
        int len=s.length();
        if(len%2!=0){
            return false;
        }
        stack<char> chars;
        for(int i=0;i<len;i++){
            if(!chars.empty()){
                if(sign(i,chars,s)){
                    chars.pop();
                }else{
                    chars.push(s[i]);
                }
            }else{
                chars.push(s[i]);
            }
        }
        if(chars.empty()){
            return true;
        }
        return false;
    }
};
全部评论

相关推荐

榕城小榕树:1200单休,我去干点啥别的不好
点赞 评论 收藏
分享
评论
3
收藏
分享

创作者周榜

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