Valid Parentheses

LeetCode #20


Description:

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

Example:

Note

Idea:

Elegant code below.

Code:

class Solution {
public:
    bool isValid(string s) {
        unordered_map<char, char>dict={{')', '('}, {']', '['}, {'}', '{'}};
        stack<char> c_stack;

        for(const auto & e: s){
            if(dict.find(e)==dict.end()){
                c_stack.push(e);
            }
            else{
                if(c_stack.empty()) // Nothing to pair
                    return false;
                else{
                    if(c_stack.top()!=dict[e]) // Not a pair
                        return false;
                    else
                        c_stack.pop(); // valid pair, remove from stack
                }
            }

        }

        return c_stack.empty();
    }
};

results matching ""

    No results matching ""