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

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

    这道题使用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
  • 相关阅读:
    Python包中__init__.py作用
    获取web页面xpath
    Selenium学习(Python)
    C++构造函数的选择
    分布式实时处理系统——C++高性能编程
    构建之法(邹欣)
    分布式实时处理系统——通信基础
    go语言-csp模型-并发通道
    redis.conf 配置说明
    Linux fork()一个进程内核态的变化
  • 原文地址:https://www.cnblogs.com/immjc/p/7660254.html
Copyright © 2011-2022 走看看