第六天-补打卡

142 阅读1分钟

题目如下:

看到这个题,我试了半天,没有一点思路,然后就去看别人的代码学习,最终通过借鉴别人的代码,成功解决题目,代码如下:

class Solution(object):
    def isValid(self, s):
        if len(s)==0 or len(s)%2==1:
            return True
        lists=['(','{','[']
        dicts={')':'(','}':'{',']':'['}
        left=[]
        if s[0] in dicts:
            return False
        for i in s:
            if i in lists:
                left.append(i)
            elif left[-1]==dicts[i]:
                left.pop()
            elif left[-1]!=dicts[i]:
                return False
        if not left:
            return True
        else :
            return False

通过栈的方式解决问题,今天学到了,下面看看官方给的代码,也是用栈的方式,但是很简洁。

class Solution(object):
    def isValid(self, s):
        mapping = {")": "(", "}": "{", "]": "["}
        for char in s:
            if char in mapping:
                top_element = stack.pop() if stack else '#'
                if mapping[char] != top_element:
                    return False
            else:
                stack.append(char)
        return not stack