leetcode 20. 有效的括号

2020-11-13  本文已影响0人  Source_Chang

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();
    }
};
上一篇下一篇

猜你喜欢

热点阅读