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

Valid Parentheses——解题报告

时间:2015-05-08 10:55:44      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:leetcode      匹配   括号   


    【题目】

    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.


    【分析】

    栈的使用,比较简单。


    【代码】

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


Valid Parentheses——解题报告

标签:leetcode      匹配   括号   

原文地址:http://blog.csdn.net/puqutogether/article/details/45576349

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