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

简介: 如何找不同

389. 找不同

12.jpg

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)

13.jpg

image-20201218110917829




相关文章
|
13天前
【LeetCode-每日一题】移动零
【LeetCode-每日一题】移动零
24 1
|
4月前
|
Python
每日一题 1447. 最简分数
每日一题 1447. 最简分数
LeetCode】每日一题(4)
LeetCode】每日一题(4)
39 0
|
5月前
每日一题——移动零
每日一题——移动零
|
10月前
|
算法 C语言 索引
每日一题:LeetCode-283. 移动零
每日一题:LeetCode-283. 移动零
【LeetCode】每日一题(2)
【LeetCode】每日一题(2)
61 0
每日一题——后继者
每日一题——后继者
81 0
每日一题——后继者
每日一题:Leetcode283 移动零
每日一题:Leetcode283 移动零
|
人工智能 算法 物联网
每日一题(day1)
每日一题(day1)
169 2
每日一题(day1)