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.

 

Subscribe to see which companies asked this question

class Solution {
public:
    bool isValid(string s) {
        stack<char> store;
        for (auto c : s) {
            if (c == '(' || c == '{' || c == '[')
                store.push(c);
            else {
                if (store.empty()) return false;
                if (c == ')' && store.top() == '('){
                    store.pop();
                }
                else if (c == '}' && store.top() == '{'){
                    store.pop();
                }
                else if (c == ']' && store.top() == '['){
                    store.pop();
                }
                else
                    return false;
            }
        }
        return store.empty();
    }
};

 

posted @ 2016-10-03 23:23  wxquare  阅读(141)  评论(0编辑  收藏  举报