Simple C++ solution with a little trick


  • 0
    J

    Just a little trick by pushing one meaningless element to the stack at first,
    so you don't have to worry about the stack being empty.
    Actually it's the same, just make the codes more concise.

    class Solution {
    public:
        bool isValid(string s) {
            stack<char> a;
            a.push('.');
            for (int i = 0; i < s.size(); i++) {
                switch (s[i]) {
                    case '(':
                    case '[':
                    case '{': a.push(s[i]);break;
                    case ')': if(a.top() != '(') return false; 
                              else a.pop(); break;
                    case ']': if(a.top() != '[') return false; 
                              else a.pop(); break;
                    case '}': if(a.top() != '{') return false; 
                              else a.pop(); break;
                }
            }
            return (a.size() == 1);
        }
    };

  • 0
    E

    why you need to have a.push('.')


  • 0
    V

    @emma.an
    if you input ()[]{}
    we must be pop ( [ { ,so a.size() == 0
    but ()[]{} is true.

    ps. sorry , my english so poor.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.