Loading

Leetcode - 20. 有效的括号

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

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

示例 1:

输入:s = "()"
输出:true

示例 2:

输入:s = "()[]{}"
输出:true

示例 3:

输入:s = "(]"
输出:false

示例 4:

输入:s = "([)]"
输出:false

示例 5:

输入:s = "{[]}"
输出:true

提示:

  • 1 <= s.length <= 104
  • s 仅由括号 '()[]{}' 组成

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

(错误)解1 2021/8/29 O(n)

def isValid(s: str) -> bool:
    len=s.__len__()
    if len%2==1: return False
    # ([({[[]]})])
    # 括号,要么左,要么右
    d={
        '(': ')',
        '[': ']',
        '{': '}',
    }
    zuo=('(','[','{')
    you=(')',']','}')
    if s[0] in you: return False
    l=r=0
    while l<len:
        ### 超时 - 1
        if s[r] in you: return False
        ### 超时 - 1
        while r<len and s[r] in zuo:
            r+=1
        if r==len: return False
        # 开始消消乐
        tmp=r-1
        while tmp>=l and r<len and d[s[tmp]]==s[r]:
            tmp-=1;r+=1
        # 一轮消完了
        if tmp<l:
            l=r
        else: return False
    return True

if __name__ == '__main__':
    print(isValid(']]'))
    print(isValid('(]'))
    print(isValid('([({[[]]})])'))
    print(isValid('([([[[]]})])'))
    print(isValid('(([({[[]]})])'))
    print(isValid('([({)[[])]})])'))
    print(isValid('()[]{}'))
    print(isValid('()'))
    print(isValid('(]'))
    print(isValid('([)]'))
    print(isValid('{[]}'))
    ### 超时
    # 1
    print(isValid('(){}}{'))
    ### 错误
    # 1
    print(isValid('(([]){})'))

posted @ 2021-08-29 19:11  wwcg2235  阅读(36)  评论(0)    收藏  举报