zoukankan      html  css  js  c++  java
  • [LeetCode] 20 Valid Parentheses 有效的括号

    [LeetCode]20 Valid Parentheses 有效的括号

    Description

    Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

    An input string is valid if:

    1. Open brackets must be closed by the same type of brackets.
    2. Open brackets must be closed in the correct order.

    Note that an empty string is also considered valid.

    Example

    Example 1:
    Input: "()"
    Output: true
    
    Example 2:
    Input: "()[]{}"
    Output: true
    
    Example 3:
    Input: "(]"
    Output: false
    
    Example 4:
    Input: "([)]"
    Output: false
    
    Example 5:
    Input: "{[]}"
    Output: true
    

    题意

    给定一个只包括 '('')''{''}''['']' 的字符串,判断字符串是否有效。
    有效字符串需满足:

    1. 左括号必须用相同类型的右括号闭合。
    2. 左括号必须以正确的顺序闭合。

    注意空字符串可被认为是有效字符串。

    题解

    用栈模拟即可,注意开个map,而不是通过多次判断可以节约时间。

    代码

    class Solution {
    public:
        bool isValid(string s) {
            bool res = true;
            
            if (s.size() == 0) return res;
            
            map <char, char> mp = { {')','('}, {'}','{'}, {']','['} };
            stack<char> st;
            
            for (int i=0; i<s.size(); ++i)
            {
                if ((s[i] == '(') || (s[i] == '{') || (s[i] == '[') )
                    st.push(s[i]);
                else
                {
                    if (!st.empty() && st.top() == mp[s[i]])
                    {
                        st.pop();
                    }
                    else
                    {
                        res = false;
                        break;
                    }  
                }
            }
            if (!st.empty())
                res = false;
            
            return res;
        }
    };       
    
  • 相关阅读:
    GitLab用户权限管理
    类似vant中的tab实现
    Gitgitee/github/gitlab账号分离
    Vim操作
    partition by 用法
    crontab执行feat_gen.sh时,报错找不到pyspark
    SQL同一个字段出现null和0值,有何区别,原因是什么?left join导致null值出现,case when导致0值出现
    linux 定时任务crontab的用法
    卡方检验
    ROC与AUC
  • 原文地址:https://www.cnblogs.com/caomingpei/p/10624915.html
Copyright © 2011-2022 走看看