[LeetCode - Python]844. 比较;含退格的字符串(Easy);415. 字符串相加(Easy)

1.题目

844. 比较含退格的字符串(Easy)
[LeetCode - Python]844. 比较;含退格的字符串(Easy);415. 字符串相加(Easy)_第1张图片

1.代码:

class Solution:
    def backspaceCompare(self, s: str, t: str) -> bool:
        # 暴力法
        s = list(s)
        t = list(t)
        M = 0
        N = 0

        for i in range(len(s)):
            i -=M 
            if s[i] == '#' :
                if i > 0 :
                    s.pop(i)
                    s.pop(i-1)
                    M+=2
                else :
                    s.pop(i)
                    M+=1


        for i in range(len(t)):
            i-=N
            if t[i] == '#':
                if i > 0:
                    t.pop(i)
                    t.pop(i-1)
                    N+=2
                else :
                    t.pop(i)
                    N+=1
        return 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 temp

    def backspaceCompare(self, s: str, t: str) -> bool:
        return self.Tuige(s) == self.Tuige(t)

在这里插入图片描述

2.题目:

415. 字符串相加(Easy)
[LeetCode - Python]844. 比较;含退格的字符串(Easy);415. 字符串相加(Easy)_第2张图片

2.代码:

class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        # 暴力双指针,尾部开始向前相加,最后反转
        # 效率低
        N1 , N2 = len(num1)-1 ,len(num2)-1
        temp =  0
        ret = []
        while N1>= 0 or N2>= 0 :
            if N2 == -1 and N1!= -1:
                s1 = int(num1[N1])
                N1-=1
                s2 = 0
            elif N1 == -1 and N2!= -1:
                s2 = int (num2[N2]) 
                N2-=1
                s1 = 0
            else:
                s1 = int(num1[N1])
                s2 = int(num2[N2]) 
                N1-=1
                N2-=1
            Sum =  s1 + s2 + temp
            if Sum >= 10 :
                temp = 1 
                ret.append(str(Sum -10))
            else :
                temp = 0  
                ret.append(str(Sum)) 

        if temp == 1:
            ret.append("1")
            temp = 0

        ret.reverse()
        return ''.join(ret)
class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        # 双指针,尾部开始向前相加,最后反转
        # 时间稍微节省不少
        N1 , N2 = len(num1)-1 ,len(num2)-1
        temp =  0
        ret = []
        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 0
            N1 -=1
            N2 -=1
            sum = n11 + n22 +temp
            ret.append(str(sum%10))     # %  取余数除
            temp = sum // 10            # // 去余数除
        return ''.join(ret[::-1])

在这里插入图片描述

你可能感兴趣的:(leetcode,python,算法)