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> c;
        int len=s.length();
        c.push(s[0]);
        char tmp=c.top();
        for(int i=1;i<len;i++){
            if(tmp=='(' && s[i]==')'){
                c.pop();
                if(!c.empty()) tmp=c.top();
                continue;
            }
            if(tmp=='{' && s[i]=='}'){
                c.pop();
                if(!c.empty()) tmp=c.top();
                continue;
            }
            if(tmp=='[' && s[i]==']'){
                c.pop();
                if(!c.empty()) tmp=c.top();
                continue;
            }
            c.push(s[i]);
            tmp=s[i];
        }
    if(c.empty()) return true;
    else          return false;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章