首页 > 其他 > 详细

20. Valid Parentheses

时间:2019-04-10 15:28:41      阅读:126      评论:0      收藏:0      [点我收藏+]

description:

check whether the (){}[] is valid(is pair)
Note:

Example:

Example 1:

Input: "()"
Output: true
Example 2:

Input: "()[]{}"
Output: true
Example 3:

Input: "(]"
Output: false
Example 4:

Input: "([)]"
Output: false
Example 5:

Input: "{[]}"
Output: true

my answer:

感恩

my answer

一眼想到堆栈,奈何堆栈没有想起我,堆栈的用法get一下ok吧...

大佬的answer:

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

relative point get√:

stackres; //definite a stack
stack.top(); // the element on the top of the stack
stack.push(xxx); // push a element on the top of the stack
stack.pop(); // pop the element on the top of the stack
stack.empty();

hint :

20. Valid Parentheses

原文:https://www.cnblogs.com/forPrometheus-jun/p/10683456.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!