• leetcode129valid-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.

    示例1

    输入

    复制
    "["

    输出

    复制
    false
    
    示例2

    输入

    复制
    "[]"

    输出

    复制
    true

    class Solution {
    public:
        /**
         *
         * @param s string字符串
         * @return bool布尔型
         */
        bool isValid(string s) {
            // write code here
            int len=s.size();
            stack <char> sta;
            for (int i=0;i<len;i++){
                if (s[i]=='(')sta.push(')');
                else if (s[i]=='[') sta.push(']');
                else if (s[i]=='{')sta.push('}');
                else if (sta.empty())return false;
                else if (sta.top()!=s[i])return false;
                else sta.pop();
                
            }
            return sta.empty();
        }
    };
  • 相关阅读:
    最短路径 Floyd && spfa
    queue 优先队列
    POJ Wormholes 最短路径 ballman_ ford 有负环
    上帝造题五分钟
    算法提高 新建Microsoft Word文档
    算法训练 最短路
    Ubuntu14 Could not open file /var/lib/dpkg/status
    MongoDB权威指南<2> 1-1 MongoDB 介绍
    SaltStack Char03 实践案例
    ELK Stack
  • 原文地址:https://www.cnblogs.com/hrnn/p/13439712.html
Copyright © 2020-2023  润新知