leetcode 20. 有效的括号

leetcode

C++:

class Solution {
public:
    bool isValid(string s) {

        std::stack 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. 有效的括号)