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
  • 相关阅读:
    2019省赛训练组队赛4.9周二 2017浙江省赛
    #Leetcode# 49. Group Anagrams
    #Leetcode# 57. Insert Interval
    POJ 2195 Going Home
    HDU 2255 奔小康赚大钱
    HDU 1083 Courses
    HDU 2063 过山车
    POJ 3041 Asteroids
    指针的妙处
    jzoj 6273. 2019.8.4【NOIP提高组A】欠钱 (money)
  • 原文地址:https://www.cnblogs.com/immjc/p/7660254.html
Copyright © 2011-2022 走看看