每日一题20201218(389. 找不同)

389. 找不同

image-20201218105549144

暴力法

使用map或者数组(因为只包含小写字母,大小固定,所以可以用数组)存放每个元素的出现次数,在s里面的次数+1,在t里面出现就-1,最后找到哪个字符是-1,就可以判断他是多出的字符了。

class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        data = {}
        i = 0
        while i < len(s) or i < len(t):
            if i < len(s):
                data[s[i]] = data.get(s[i], 0) + 1
            data[t[i]] = data.get(t[i], 0) - 1
            i += 1
        for k, v in data.items():
            if v == -1:
                return k
        return ""

利用ascii码

我们知道ascii码每个字母是不同的,

用t的所有字符加起来的ascii码-s的所有字符加起来的ascii码,

最后得到的肯定是多出来字符的ascii码,最后把它转回成字符串。
class Solution:
    
    def findTheDifference(self, s: str, t: str) -> str:
        sc = sum(ord(x) for x in s)
        tc = sum(ord(x) for x in t)
        return chr(tc-sc)
        # 一句话
        # return chr(sum(ord(x) for x in t) - sum(ord(x) for x in s))

优化后少遍历一次

class Solution:

    def findTheDifference(self, s: str, t: str) -> str:
        i = 0
        sc, tc = 0, 0
        while i < len(s):
            sc += ord(s[i])
            tc += ord(t[i])
            i += 1
        return chr(tc + ord(t[-1]) - sc)

image-20201218110917829

原文地址:https://www.cnblogs.com/we8fans/p/14153932.html