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

  • 相关阅读:
    进程相关知识点
    vue上传
    Storageclass 外挂NFS配置与应用
    centos强制关机后,网卡无法启动
    前端工程化2-webpack使用与学习
    android应用获取应用签名
    js获取tif格式图片的dpi
    查询生成二级树型结构最高效的方式
    03解决隔离的方案
    02SingleSpa实战
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4034105.html
Copyright © 2011-2022 走看看