zoukankan      html  css  js  c++  java
  • LeetCode 20. 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.

    因为例如"([{}])"也是正确的,明显我们要用到栈,如果匹配(即对应的是左右括号)则出栈,否则入栈,最后栈为空为真,否则为假

    但是要注意“]["也为假,但是LeetCode的测试用例并没有考虑到这种情况,因为我第一次提交的时候也没有考虑到这种情况但是提交

    却通过了

    class Solution {
    public:
        bool isValid(string s) {
            if (0 == s.size())return true;
            map<char, int> map;
            map['('] = 0;map['['] = 1;map['{'] = 2;map[')'] = 3;map[']'] = 4;map['}'] = 5;
            stack<char> sta;
            for (size_t i = 0;i < s.size();++i)
            {
                if (sta.size()&&(map[s[i]] != map[sta.top()] && map[s[i]] % 3 == map[sta.top()] % 3)&&map[sta.top()]<map[s[i]])
                {
                    sta.pop();
                }
                else
                    sta.push(s[i]);
            }
            if (sta.size())return false;
            else return true;
        }
    };
  • 相关阅读:
    软工实践-Alpha 冲刺 (7/10)
    软工实践-Alpha 冲刺 (6/10)
    软工实践-Alpha 冲刺 (5/10)
    软工实践-Alpha 冲刺 (4/10)
    BETA 版冲刺前准备
    第十一次作业
    Alpha 冲刺 (9/10)
    Alpha 冲刺 (8/10)
    Alpha 冲刺 (7/10)
    Alpha 冲刺 (6/10)
  • 原文地址:https://www.cnblogs.com/csudanli/p/5882338.html
Copyright © 2011-2022 走看看