所以这是leetcode的问题。我有两个字符串 s 和 t。 字符串 t 是通过随机打乱字符串 s 生成的,然后在随机位置再添加一个字母。 我要退回添加到 t 的那封信。
这是我的问题解决方案:
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
dict_s = {}
dict_t = {}
# loop through string and add the frequency into a dictionary
for i in s:
if i not in dict_s:
dict_s[i] = 1
else:
dict_s[i] += 1
for i in t:
if i not in dict_t:
dict_t[i] = 1
else:
dict_t[i] += 1
# compare the frequency of both dictionaries
for key, value in dict_t.items():
if key not in dict_s:
difference = key
elif value != dict_s[key]:
difference = key
return difference
它说我已经使用了 17.20MB,运行时间为 42MS 我知道在日常编码和实践中这些数字有点无关紧要,但是如果我正在从事更大规模的项目,我的解决方案中是否存在任何明显的不当实践,可能会在未来导致严重的内存问题?
您可以使用 one 字典而不是两个。数一串,减去另一串。