思路1:替换,使用字母集合
时间复杂度O(N2):replace函数和while循环
空间复杂度O(N):replace函数
from string import ascii_lowercase
class Solution:
def removeDuplicates(self, S: str) -> str:
words = {2*c for c in ascii_lowercase} # 双字母集合
prelen = -1
while prelen!=len(S):
prelen = len(S)
for ch in words:
S = S.replace(ch,'')
return S
思路2:使用栈记录不连续重复的元素
遍历时,栈中存放上前一个元素,若相等,则出栈,不相等,则入栈
时间复杂度O(N):遍历
空间复杂度O(N):整个字符串不重复
class Solution:
def removeDuplicates(self, S: str) -> str:
stack = []
for ch in S:
if not stack or ch!=stack[-1]:
stack.append(ch)
else:
stack.pop(-1)
return "".join(stack)