Sharing my simple cpp code with 2ms


  • 13
    E
        class Solution {
        public:
            bool isValid(string s) {
                map<char, char> parenth_dict;
                parenth_dict['('] = ')';
                parenth_dict['{'] = '}';
                parenth_dict['['] = ']';
                
                stack<char> aux;
                for (int i = 0; i < s.size(); i++) {
                    if (s[i] == '(' || s[i] == '{' || s[i] == '[') 
                        aux.push(s[i]);
                    else if (aux.empty() || parenth_dict[aux.top()] != s[i])
                        return false;
                    else
                        aux.pop();
                }
                
                return aux.empty();
                
            }
    
    };

  • 0
    F

    Mine is also in 2ms:

    class Solution {
    public:
        bool isValid(string s) {
          string leftBrackets = "([{";
         string rightBrackets = ")]}";
         stack<char> leftSide;
         for(unsigned i = 0; i < s.length(); i++){
             if(leftBrackets.find(s[i]) != string::npos){
                 leftSide.push(s[i]);
             }
             else if(rightBrackets.find(s[i]) != string::npos){
                 //Check the corresponding left bracket
                 if(!(leftSide.empty()) && leftBrackets.find(leftSide.top()) == rightBrackets.find(s[i]) ) {
                     leftSide.pop();
                     continue;
                 }
                 else{
                     return false;
                 }
             }
             else{
                 continue;
             }
         }
         return leftSide.empty();
        }
    };

  • 0
    F

    When no matching left parenthesis is found, why the right parenthesis is pushed the stack?


  • 0
    A

    @Felin, you should re-read the code, the right parenthesis is never pushed to the stack. Btw, this is a beautiful code.


Log in to reply
 

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