1.题目
844. 比较含退格的字符串(Easy)
1.代码:
class Solution:def backspaceCompare(self, s: str, t: str) -> bool:# 暴力法s = list(s)t = list(t)M = 0N = 0for i in range(len(s)):i -=M if s[i] == '#' :if i > 0 :s.pop(i)s.pop(i-1)M+=2else :s.pop(i)M+=1for i in range(len(t)):i-=Nif t[i] == '#':if i > 0:t.pop(i)t.pop(i-1)N+=2else :t.pop(i)N+=1return s == t
class Solution:#新建子方法,堆栈。def Tuige(self,ss:str):ss = list(ss)temp = []for i in ss:if i != '#':temp.append(i)elif temp:temp.pop()return tempdef backspaceCompare(self, s: str, t: str) -> bool:return self.Tuige(s) == self.Tuige(t)
2.题目:
415. 字符串相加(Easy)
2.代码:
class Solution:def addStrings(self, num1: str, num2: str) -> str:# 暴力双指针,尾部开始向前相加,最后反转# 效率低N1 , N2 = len(num1)-1 ,len(num2)-1temp = 0ret = []while N1>= 0 or N2>= 0 :if N2 == -1 and N1!= -1:s1 = int(num1[N1])N1-=1s2 = 0elif N1 == -1 and N2!= -1:s2 = int (num2[N2]) N2-=1s1 = 0else:s1 = int(num1[N1])s2 = int(num2[N2]) N1-=1N2-=1Sum = s1 + s2 + tempif Sum >= 10 :temp = 1 ret.append(str(Sum -10))else :temp = 0 ret.append(str(Sum)) if temp == 1:ret.append("1")temp = 0ret.reverse()return ''.join(ret)
class Solution:def addStrings(self, num1: str, num2: str) -> str:# 双指针,尾部开始向前相加,最后反转# 时间稍微节省不少N1 , N2 = len(num1)-1 ,len(num2)-1temp = 0ret = []while N1>= 0 or N2>= 0 or temp != 0 :n11 = int(num1[N1]) if N1 >= 0 else 0 n22 = int(num2[N2]) if N2 >= 0 else 0N1 -=1N2 -=1sum = n11 + n22 +tempret.append(str(sum%10)) # % 取余数除temp = sum // 10 # // 去余数除return ''.join(ret[::-1])