• leetcode第20题--Valid Parentheses


    Problem:

    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.

    判断输入的括号是不是合法。这题在大二的时候就遇到过了。想不到我的记性这么好。因为当时我什么都不懂,刚学数据结构,然后有个ACMer是助教,他给我讲解了这题。然后我就一直都记得了。也不知道那个师兄现在在哪里牛逼。

    回到题目,就是用栈实现。

    class Solution {
        private:
        char anti(char c)
        {
            if (c == ']')
                return '[';
            if (c == ')')
                return '(';
            if (c == '}')
                return '{';
        }
    public:
        bool isValid(string s) {
            int len = s.size();
            if (len%2)
            { return false;}
            if(s.size() == 0 || s[0] == ')' || s[0] == ']' || s[0] == '}')
                return false;
            stack<char> st;
            for (int i = 0; i < len; i++)
            {
                if (s[i] == '(' || s[i] == '{' || s[i] == '[')
                    st.push(s[i]);
                else
                    if (st.top() == anti(s[i]))
                        st.pop();
                    else
                        return false;
            }
            if (st.empty())
                return true;
            else
                return false;
        }
    };

    代码写得有点挫,大概就是这个思路,然后Accept了

  • 相关阅读:
    .csproj文件
    堆栈
    数据库操作(一)
    Math数学函数
    SSM框架下各个层的解释说明
    MyBatis DAO层传递参数到mapping.xml
    Spring MVC3在controller和视图之间传递参数的方法
    注册/登陆界面验证码的作用及代码实现
    input中name和id的区别
    <mvc:default-servlet-handler/>的作用
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4034105.html
Copyright © 2020-2023  润新知