leetcode——20. 有效的括号

简单题:

用栈实现:

class Solution:
    def isValid(self, s: str) -> bool:
        if s=='':
            return True
        if len(s)==1:
            return False
        stack=[]
        i=0
        while i<len(s):
            if s[i] in '({[':
                stack.append(s[i])
                i+=1
                if i==len(s):
                    return False
            else:
                if stack==[]:
                    return False
                if (s[i]==')' and stack.pop()=='(' )or (s[i]=='}' and stack.pop()=='{') or (s[i]==']' and stack.pop()=='['):
                    i+=1
                else:
                    return False
        if stack!=[]:
            return False
        return True
执行用时 :44 ms, 在所有 python3 提交中击败了84.49%的用户
内存消耗 :13.8 MB, 在所有 python3 提交中击败了5.51%的用户
 
                                        ——2019.10.17

猜你喜欢

转载自www.cnblogs.com/taoyuxin/p/11690893.html
今日推荐