美文网首页
leetcode 20. 有效的括号

leetcode 20. 有效的括号

作者: Source_Chang | 来源:发表于2020-11-13 19:22 被阅读0次

    leetcode

    C++:

    class Solution {
    public:
        bool isValid(string s) {
    
            std::stack<char> charStack;
            for ( int i = 0; i < s.size(); ++i ) {
    
                if ( s[i] == '(' || s[i] == '{' || s[i] == '[' ) {
    
                    charStack.push( s[i] );
    
                } else if ( s[i] == ')' || s[i] == '}' || s[i] == ']' ) {
    
                    if ( charStack.empty() ) {
    
                        return false;
                    }
    
                    if ( ( s[i] == ')' && charStack.top() == '(' ) || 
                         ( s[i] == '}' && charStack.top() == '{' ) || 
                         ( s[i] == ']' && charStack.top() == '[' ) ) {
    
                        charStack.pop();
    
                        continue;
                    }
    
                    return false;
                }
            }
    
            return charStack.empty();
        }
    };
    

    相关文章

      网友评论

          本文标题:leetcode 20. 有效的括号

          本文链接:https://www.haomeiwen.com/subject/ovmuvktx.html