Valid Parentheses

来源:互联网 发布:最好的大六壬排盘软件 编辑:程序博客网 时间:2024/05/29 08:07

题目:

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.

思路:

遇到 “(”  “{”  “[”,进入堆栈;

如果不是,查看堆栈中是否为空,为空,false。

                    不为空,查看顶端字符与当前字符是否配对,并出栈。

代码:

class Solution {public:    bool isValid(string s) {        if(s.empty())            return false;        int len=s.length();        stack<char>stk;                for(int i=0;i<len;i++){            if(s[i]=='['||s[i]=='{'||s[i]=='('){                stk.push(s[i]);            }else{                if(stk.empty()){                    return false;                }else if(stk.top()=='{'&&'}'==s[i]){                    stk.pop();                }else if(stk.top()=='['&&']'==s[i]){                    stk.pop();                }else if(stk.top()=='('&&')'==s[i]){                    stk.pop();                }else                    return false;            }        }        return stk.empty();//假如出现“()”,没有这句话,就会没有数值输出    }};


0 0
原创粉丝点击