**(leetcode_string) Valid Parentheses

来源:互联网 发布:python检测sql注入 编辑:程序博客网 时间:2024/06/08 18:45

Valid Parentheses

 Total Accepted: 27208 Total Submissions: 97024My Submissions

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.

Show Tags
 Stack String
Have you met this question in a real interview? 
Yes
 
No

Discuss

利用stack~!

class Solution {public:    bool isValid(string s) {        stack<char> stk;        int i;        for(i=0;i<s.length();i++){            if(s[i]=='(' || s[i]=='[' || s[i]=='{')                stk.push(s[i]);            else{                if(!stk.empty()&&((stk.top()=='('&&s[i]==')') ||(stk.top()=='['&&s[i]==']')||(stk.top()=='{'&&s[i]=='}')))                        stk.pop();                else                    return false;            }        }        return stk.empty();    }};


0 0
原创粉丝点击