My c++ 0ms clear solution with stack and map


  • 0
    Y
    class Solution {
    public:
        bool isValid (string s) {
          std::stack<char> cache;
          std::map<char,char> symbolPairs = {{')','('},{']','['},{'}','{'}};
          for (std::string::iterator iter = s.begin(); iter<s.end(); iter++)
          {
            char letter = *iter;
            if (letter == '(' || letter == '[' || letter == '{') //first half
              cache.push (letter);
            else if (letter == ')' || letter == ']' || letter == '}')
            {
              if (cache.size()==0)
                return false;
              char potentialMatch = cache.top();
              cache.pop();
              if (potentialMatch != symbolPairs.at(letter))
                return false;
            }
          }
          if (cache.size() > 0)
            return false;
          else
            return true; 
        }
    };
    

Log in to reply
 

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