Monday, December 15, 2014

Valid Parentheses

Q:
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.

T:
When seeing a left parenthesis, push it to the stack. When seeing a right parenthesis, pop the stack to see whether there is a match.

A:


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

No comments:

Post a Comment