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

【leetcode】20. Valid Parentheses

时间:2015-07-14 11:22:05      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:leetcode   parenthese   algorithm   

@requires_authorization
@author johnsondu
@create_time 2015.7.13 11:03
@url [valid parentheses](https://leetcode.com/problems/valid-parentheses/)
/*****************
 * 类别: 栈模拟判断
 * 时间复杂度: O(n)
 * 空间复杂度: O(n)
 ****************/
class Solution {
public:
    bool isValid(string s) {
        stack<char> st;
        int len = s.size();
        for(int i = 0; i < len; i ++){
            if(s[i] == ‘]‘ || s[i] == ‘}‘ || s[i] == ‘)‘){
                if(st.empty()){
                    return false;
                }
            }
            else{
                st.push(s[i]);
                continue;
            }
            if(s[i] == ‘]‘){
                char ch = st.top();
                st.pop();
                if(ch != ‘[‘) return false;
                continue;
            }
            if(s[i] == ‘)‘){
                char ch = st.top();
                st.pop();
                if(ch != ‘(‘) return false;
                continue;
            }
            if(s[i] == ‘}‘){
                char ch = st.top();
                st.pop();
                if(ch != ‘{‘) return false;
                continue;
            }
        }
        if(st.empty()) return true;
        else return false;
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

【leetcode】20. Valid Parentheses

标签:leetcode   parenthese   algorithm   

原文地址:http://blog.csdn.net/zone_programming/article/details/46874895

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