一. 题目
-
题目
-
示例
二. 方法一: 栈
-
解题思路
- 将列表中的元素依次进栈
- 如果栈顶的3个元素一次是"c", “b”, “a”, 则弹出这3个元素
- 当遍历完后, 栈为空, 则返回True; 否则, 返回False
-
解题代码
def isValid(self, S: str) -> bool: stack = [] for ele in S: stack.append(ele) if len(stack) >= 3 and stack[-1] == "c" and stack[-2] == "b" and stack[-3] == "a": stack.pop() stack.pop() stack.pop() if stack: return False else: return True
-
分析
时间复杂度: O(n)
空间复杂度: O(n)
三. 方法二: 字符串替换
-
解题思路
-
解题代码
def isValid(self, S: str) -> bool: while "abc" in S: S = S.replace("abc", "") return S == ""
-
分析
时间复杂度: O(n)
空间复杂度: O(1)