查找数组中的差异

问题描述 投票:0回答:3

这里是原始问题的链接:https://leetcode.com/problems/find-the-difference/

这是我的代码。我不断收到“索引超出范围”错误,但我不确定为什么。

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]
python arrays structure
3个回答
0
投票

根据问题,字符串t的长度1将大于字符串s的长度。现在想象一下,假设通过在字符串s的末尾附加随机字符形成字符串t时会发生什么。

完成字符串s

的所有字符处理后,将继续检查字符串t的最后一个字符,但字符串s中对应索引处的字符不是当前,并导致Index Out Of Range

有更好的方法来解决这个问题,请再努力。


0
投票

假设您输入这2作为输入


0
投票

您的问题是,到达列表末尾时您不会停止迭代。如果将while条件更改为:

© www.soinside.com 2019 - 2024. All rights reserved.