26. 删除有序数组中的重复项
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
slow=0
fast=1
while fast<len(nums):
if nums[fast]!=nums[slow]:
slow+=1(因为需要向slow中填数据,应该先加1,避免覆盖原有数据)
nums[slow]=nums[fast]
fast+=1
return slow+1
844. 比较含退格的字符串
class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
fast1=1
slow1=0
fast2=1
slow2=0
list_s=list(s)
list_t=list(t)
while fast1<len(list_s) and slow1>=0:
if s[fast1]!='#':
slow1+=1
list_s[slow1]=list_s[fast1]
else:
slow1-=1(在测试"a##c" "#a#c"时出错,不知道#号到0位置应该怎么处理?
解答:由于 # 号只会消除左边的一个字符,所以对右边的字符无影响,所以我们选择从后往前遍历 S,T 字符串。
fast1+=1
list_s=list_s[0:slow1+1]
while fast2<len(list_t) and slow2>=0:
if t[fast2]!='#':
slow2+=1
list_t[slow2]=list_t[fast2]
else:
slow2-=1
fast2+=1
list_t=list_t[0:slow2+1]
if list_s==list_t:
return True
else:
return False
用栈的思想实现更简单,记住!
class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
def build(s:str)->str:
stack=[]
for i in s:
if i != '#':
stack.append(i)
elif stack:(这个用法要记住)
stack.pop()
return "".join(stack)
return build(S)==build(T)