题解 | #有效括号序列#

有效括号序列

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

class Solution {
public:
    /**
     * 
     * @param s string字符串 
     * @return bool布尔型
     */
    bool isValid(string s) {
        // write code here
        stack<char> st;
        int i = 0;
        while(i < s.length()){
            if(s[i] == '(' || s[i] == '[' || s[i] == '{'){
                st.push(s[i]);
            }
            else{
                if(s[i] == ')'){
                    if(st.empty() || st.top() != '('){
                        return false;
                    }
                    else{
                        st.pop();
                    }
                }
                else if(s[i] == ']'){
                    if(st.empty() || st.top() != '['){
                        return false;
                    }
                    else{
                        st.pop();
                    }
                }
                else{
                    if(st.empty() || st.top() != '{'){
                        return false;
                    }
                    else{
                        st.pop();
                    }
                }
            }
            i++;
        }
        
        if(!st.empty()){
            return false;
        }
        
        return true;
        
    }
};
全部评论

相关推荐

06-02 15:53
阳光学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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