想着和3174.clearDigits一样做,由于提交时候由于递归的内存使用问题AC不了。下面是使用递归的代码,理论上应该是没问题的。时间超时解决了,内存还是超出了。
class Solution:
def removeStars(self, s: str) -> str:
def remove(my_str: str, index: int) -> str:
while index < len(my_str):
if my_str[index] == '*':
new_str = my_str[:index - 1] + my_str[index + 1:]
index -= 1
return remove(new_str, index)
index += 1
return my_str
return remove(s, 0)
直接根据最简单的题意去写:
class Solution:
def removeStars(self, s: str) -> str:
i, n = 0, len(s)
while i < n:
if s[i] == '*':
s = s[:i - 1] + s[i + 1:]
i -= 1
n -= 2
else:
i += 1
return s
根据栈去维护:
class Solution:
# 官方的参考答案还是非常巧妙的使用栈维护,构建新的字符串
def removeStars(self, s: str) -> str:
res = []
for c in s:
if c != '*':
res.append(c)
elif res:
res.pop()
return ''.join(res)