Sunday, April 26, 2015

[LeetCode] Valid Parentheses

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.

class Solution {
public:
    bool isValid(string s) {
        stack<char> pStack;
        unordered_map<char,char> map;
        map['}'] = '{';
        map[']'] = '[';
        map[')'] = '(';
        for(int i=0;i<s.length();i++)
        {
            if(s[i] == '(' || s[i] == '{' || s[i] == '[')
            {
                pStack.push(s[i]);
            }
            else if (pStack.empty())
            {
                return false;
            }
            else if(map[s[i]] == pStack.top())
            {
                pStack.pop();
            }
            else
            {
                return false;
            }
        }
        return pStack.empty();
    }
};