Valid Parentheses 有效括号

来源:互联网 发布:外置网络打印服务器 编辑:程序博客网 时间:2024/05/08 07:52

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) {        if(s.length()%2 != 0)            return false;        if(s.length() == 0)            return true;                stack<char> stk;                for(int i=0;i<s.length();i++){            if(s[i] == ')' || s[i] == ']' || s[i] == '}'){                if(stk.empty()){                    return false;                }                if(isDoubleStr(stk.top(),s[i])){                    stk.pop();                }else{                    return false;                }            }else{                stk.push(s[i]);            }        }                if(stk.empty())            return true;        else            return false;    }        bool isDoubleStr(char a,char b){        switch(a){            case '(':                if(b == ')')                    return true;                else                    return false;            case '[':                if(b == ']')                    return true;                else                    return false;            case '{':                if(b == '}')                    return true;                else                    return false;            default:                return false;        }    }};


0 0
原创粉丝点击