LeetCodeDiary

A Diary for solving LeetCode problems

View on GitHub
class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        # 长度为 26 的数组,用以统计字符出现次数
        str_count = [0] * 26
        # 先遍历 s,统计 s 中字符出现的次数
        for ch in s:
            str_count[ord(ch)-ord('a')] += 1
        # 再遍历 t,将出现字符对应次数减 1,
        # 当出现负值,表示对应的字符就是添加的字母
        for ch in t:
            str_count[ord(ch)-ord('a')] -= 1
            if str_count[ord(ch)-ord('a')] < 0:
                return ch
        
        return ''
# 每日一题,哈希表
# https://leetcode-cn.com/problems/find-the-difference/