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> symbol_container;

        int len = s.length();
        int i;
        for (i=0; i<len; i++){
            if (check_open_symbol(s[i])) {
                symbol_container.push(s[i]);
            } else if (check_close_symbol(s[i])) {
                if (!symbol_container.empty() && (symbol_container.top() == get_match_symbol(s[i]))) {
                    symbol_container.pop();
                } else {
                    return false;
                }
            }
        }
        if (symbol_container.empty()) {
            return true;
        } else {
            return false;
        }

    }

    bool check_open_symbol(char c) {
        if (c =='(' || c == '[' || c == '{') {
            return true;
        }
        return false;
    }

    bool check_close_symbol(char c) {
        if ( c == '}' || c == ')' || c == ']') {
            return true;
        }
        return false;
    }

    char get_match_symbol(char c) {
        if (c == '{'){
            return '}';
        } else if (c == '}') {
            return '{';
        }else if (c == '(') {
            return ')';
        }else if (c == ')') {
            return '(';
        }else if (c == ']') {
            return '[';
        }else if (c == '[') {
            return ']';
        }
    }
};

 

posted on 2016-01-07 20:29  walkwalkwalk  阅读(149)  评论(0编辑  收藏  举报

导航