• 【leetcode】20.有效的括号


    题目

    给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。有效字符串需满足:左括号必须用相同类型的右括号闭合。左括号必须以正确的顺序闭合。注意空字符串可被认为是有效字符串。

    示例 1:输入: "()"
    输出: true
    示例 2:输入: "()[]{}"
    输出: true
    示例 3:输入: "(]"
    输出: false
    示例 4:输入: "([)]"
    输出: false
    示例 5:输入: "{[]}"
    输出: true

    思路

    第一个思路
    考虑两种情况:

    1. 看括号所组成的字符串是不是一个回文字符
    2. 连续括号组成匹配项

    贴一下我弱智的代码

    
    def isValid(s):
            symbol_map = {"(":")", ")":"(",
                         "{":"}", "}":"{",
                         "[":"]", "]":"["
                         }
            if s == "":
                return True
            s = list(s)
            if len(s) % 2 != 0:
                return False
            if symbol_map[s[0]] == s[1]:
                length = len(s)
                i = 0
                while i <= length:
                    if i <= length - 1:
                        if symbol_map[s[i]] == s[i+1]:
                            i += 2
                            continue
                        else:
                            break
                    if i == length:
                        return True
            else:
                re_s = reversed(s)
                return len([1 for i in zip(s, re_s) if symbol_map[i[0]] == i[1]]) == len(s)
    if __name__ == "__main__":
        s = "()"
        print(isValid(s))
    

    代码

    参考大神的代码,如沐春风,同时也感受到了自己是多么的弱。

    class Solution:
        def isValid(self, s: str) -> bool:
            while '{}' in s or '()' in s or '[]' in s:
                s = s.replace('{}', '')
                s = s.replace('[]', '')
                s = s.replace('()', '')
            return s == ''
    
  • 相关阅读:
    [CF590C] Three States
    [CF767B] The Queue
    [CF1296F] Berland Beauty
    [CF3D] Least Cost Bracket Sequence
    YUV420 转 RGB 测试
    [POI2012] TOU-Tour de Byteotia
    [CF576C] Points on Plane
    [CF191C] Fools and Roads
    [CF1485C] Floor and Mod
    [CF1399D] Binary String To Subsequences
  • 原文地址:https://www.cnblogs.com/wemo/p/10767935.html
Copyright © 2020-2023  润新知