20. 有效的括号 (括号匹配是使用栈解决的经典问题,这道题主要是记住三种不成立的情况)

给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
 
 
 
class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        
        for item in s:
            if item == '(':
                stack.append(')')
            elif item == '[':
                stack.append(']')
            elif item == '{':
                stack.append('}')
            elif not stack or stack[-1] != item:
                return False
            else:
                stack.pop()
        
        return True if not stack else False
                 下面此3种错:
1047. 删除字符串中的所有相邻重复项 (这道题关键是思路要对)
重点:遍历每个元素的时候要去栈里看是不是和这个元素相等(前提是栈不为NULL)

class Solution:
    def removeDuplicates(self, s: str) -> str:
        res = list()
        for item in s:
            if res and res[-1] == item:
                res.pop()
            else:
                res.append(item)
        return "".join(res)  # 字符串拼接

![[Golang] 爬虫实战-用多层嵌套结构体去接收多层嵌套数据](https://img-blog.csdnimg.cn/a9509c5ed06e491a970eb764f66f6f60.png)
















