c++ 0ms solution (easy to understand)


  • 0
    class Solution {
    public:
        bool isValid(string s) {
            vector<char> vec;
            for(auto c : s)
            {
                if(c=='(' || c=='[' || c=='{')
                    vec.push_back(c);
                else if(c==')' && !vec.empty() && vec.back()=='(')
                    vec.pop_back();
                else if(c==']' && !vec.empty() && vec.back()=='[')
                    vec.pop_back();
                else if(c=='}' && !vec.empty() && vec.back()=='{')
                    vec.pop_back();
                else
                    return false;
            }
            if(!vec.empty())
                return false;
            return true;
        }
    };

Log in to reply
 

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