leetcode - Valid Parentheses

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 isPair(char a, char b){
        if(a == '(' && b == ')') return true;
        if(a == '[' && b == ']') return true;
        if(a == '{' && b == '}') return true;
        return false;
    }
    
    bool isValid(string s) {
        stack<char> strStk;
        int i=0;
        while(i<s.length()){
            if(!strStk.empty()){
                if(isPair(strStk.top(), s[i]))
                strStk.pop();
                else strStk.push(s[i]);
            }
            else strStk.push(s[i]);
            i++;
        }
        return strStk.empty() ? true : false;
    }
    

};
posted @ 2015-08-17 18:03  cnblogshnj  阅读(115)  评论(0编辑  收藏  举报