码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 20 -- Valid Parentheses

时间:2015-06-05 14:07:10      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:stack   string   

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

标签:stack   string   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!