My c++ switch case solution with stack (DRY)


  • 0
    W
    class Solution {
    public:
        bool isValid(string s) {
            stack<char> parentheses;
            for (const auto c : s) {
                char comp = '0';
                switch(c) {
                    case '(' :
                    case '{' :
                    case '[' :
                        parentheses.push(c);
                        break;
                    case ']' :
                        comp = '[';
                        break;
                    case '}' :
                        comp = '{';
                        break;
                    case ')' :
                        comp = '(';
                        break;
                    default:
                        // unreachable
                        return false;
                }
                if (comp != '0') {
                    if (parentheses.empty() || comp != parentheses.top()) 
                        return false;
                    else 
                        parentheses.pop();
                }
            }
            return parentheses.empty();
        }
    };

  • 1
    H

    Mine is similar to yours. I like your const for each loop!

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

Log in to reply
 

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