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

[LeetCode] Valid Parentheses

时间:2017-10-13 12:35:39      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:order   else   contain   ret   nta   false   括号   turn   determine   

 

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.

判断字符串中括号的有效性。

这道题使用stack来存储括号,遍历字符串中的括号。

如果遇到右括号

  这时如果stack为空,则立即返回false。

  如果这时stack中右匹配的左括号,将stack中左括号弹出stack。

  如果这时stack中没有匹配的左括号,返回false。

如果遇到左括号

  将其压入stack中。

最后判断

  如果stack中存在元素,则表示还有未匹配的左括号,返回false

  如果stack不存在元素,则表示所有括号都已匹配成功,返回true

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

 

[LeetCode] Valid Parentheses

标签:order   else   contain   ret   nta   false   括号   turn   determine   

原文地址:http://www.cnblogs.com/immjc/p/7660254.html

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