查找数组中的差异

Finding the difference in an array

这是原问题的link:https://leetcode.com/problems/find-the-difference/

这是我的代码。我不断收到 "index out of range" 错误,但不确定原因。

class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        i = 0 
        ss = list(s)
        tt = list(t)
        while ss[i] == tt[i]: 
            i += 1 
            if ss[i] != tt[i]:
                return tt[i]

根据问题,字符串 t 的长度将比字符串 s 的长度大 1。现在想象一下,当字符串 t 是通过将随机字符附加到字符串 s.

的末尾形成时会发生什么

当你处理完字符串s的所有字符后,你将继续检查字符串t的最后一个字符,但是字符串 s 中相应索引处的字符不存在,这导致 Index Out Of Range

这个题有更好的解法,再努力一下

假设您将这 2 个作为输入

s = "abcd"
t = "abcde"

在循环的第 4 圈 i=3 它将变为 4 因为 ss[i] != tt[i] 是假的 将继续下一个循环并计算这个表达式 ss[i] == tt[i] ss 的长度为 4,它会尝试访问不存在的第 5 个元素,最终会抛出 indexError 你可以尝试类似的东西:

class Solution:
def findTheDifference(self, s: str, t: str) -> str:
    i = 0 
    ss = list(s)+[None]
    tt = list(t)
    while ss[i] == tt[i]: 
        i += 1 
        if ss[i] != tt[i]:
            return tt[i]

你的问题是当你到达列表末尾时你没有停止迭代。如果您将 while 条件更改为:

while ss[i] == tt[i] and i < len(ss) and i < len(tt)

你会避开 IndexError.

另外,这种情况更适合 for 循环:

for i in range(min(len(ss), len(tt))):  # Only loop while both lists still have elements
    ...

可能您的参数大小不同。

就像 tabcdsaa 这就是你遇到这个问题的原因。

让我们假设 i 是 2

ss 将是 ctt 将抛出 index out of range

ss[i] == tt[i]