首页 > 其他 > 详细

leetcode 20 -- Valid Parentheses

时间:2015-06-05 14:03:54      阅读:234      评论:0      收藏:0      [点我收藏+]

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.


题意:
实现括号匹配


思路:
括号匹配问题我们一般使用栈来辅助,每次先判断栈是否为空,1.不为空我们则用栈顶元素和新元素进行匹配,如果匹配上则pop出栈,否则push入栈,2.如果栈为空我们就push入栈


代码:

class Solution {
public:
    bool isValid(string s) {
        stack<char> sk;
        for(char c : s){
            if(!sk.empty()){
                char tmp = sk.top();
                if((tmp == ‘(‘ && c == ‘)‘) ||
                   (tmp == ‘[‘ && c == ‘]‘) ||
                   (tmp == ‘{‘ && c == ‘}‘)){
                       sk.pop();
                   }else{
                       sk.push(c);
                   }
            }else{
                sk.push(c);
            }
        }
        if(sk.empty()){
            return true;
        }else{
            return false;
        }
    }
};

leetcode 20 -- Valid Parentheses

原文:http://blog.csdn.net/wwh578867817/article/details/46375255

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