Solution C++ with map


  • 0
    J
    class Solution {
    public:
        bool isValid(string s) {
            map<char, char> mpp = {{')','('}, {'}','{'}, {']', '['}, {'(', 0}, {'{', 0}, {'[', 0}};
            vector<char> vp;
            
            for(int i = 0; i < s.length(); i++) {
                char ch = s.at(i);
                if (mpp.find(ch) == mpp.end()) continue; // if it's not parentheses
                char exp = mpp[ch];
                if (exp == 0) { // if it's open
                    vp.push_back(ch);
                }
                else if (!vp.empty() && exp == vp.back()) { // if it's close
                    vp.pop_back();
                }
                else {
                    return false;
                }
            }
            return vp.empty();
        }
    };
    

Log in to reply
 

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