LeetCode 题解工作台

找不同

给定两个字符串 s 和 t ,它们只包含小写字母。 字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。 请找出在 t 中被添加的字母。 示例 1: 输入: s = "abcd", t = "abcde" 输出: "e" 解释: 'e' 是那个被添加的字母。 示例 2: 输入: s = …

category

4

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 哈希·表·结合·string

bolt

答案摘要

我们可以用一个哈希表或数组 统计字符串 中每个字符出现的次数,再遍历字符串 ,对于每个字符,我们在 中减去一次出现的次数,如果对应次数为负数,则说明该字符在 中出现的次数大于在 中出现的次数,因此该字符为被添加的字符。 时间复杂度 ,空间复杂度 ,其中 为字符串的长度,而 表示字符集,这里字符集为所有小写字母,所以 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定两个字符串 st ,它们只包含小写字母。

字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。

请找出在 t 中被添加的字母。

 

示例 1:

输入:s = "abcd", t = "abcde"
输出:"e"
解释:'e' 是那个被添加的字母。

示例 2:

输入:s = "", t = "y"
输出:"y"

 

提示:

  • 0 <= s.length <= 1000
  • t.length == s.length + 1
  • st 只包含小写字母
lightbulb

解题思路

方法一:计数

我们可以用一个哈希表或数组 cntcnt 统计字符串 ss 中每个字符出现的次数,再遍历字符串 tt,对于每个字符,我们在 cntcnt 中减去一次出现的次数,如果对应次数为负数,则说明该字符在 tt 中出现的次数大于在 ss 中出现的次数,因此该字符为被添加的字符。

时间复杂度 O(n)O(n),空间复杂度 O(Σ)O(|\Sigma|),其中 nn 为字符串的长度,而 Σ\Sigma 表示字符集,这里字符集为所有小写字母,所以 Σ=26|\Sigma|=26

1
2
3
4
5
6
7
8
class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        cnt = Counter(s)
        for c in t:
            cnt[c] -= 1
            if cnt[c] < 0:
                return c
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate chooses a hash table or XOR-based approach for linear time performance.

  • question_mark

    The candidate uses sorting without considering time complexity trade-offs.

  • question_mark

    The candidate effectively explains the space-time trade-off between the hash table and XOR solutions.

warning

常见陷阱

外企场景
  • error

    Using sorting without considering its time complexity can lead to suboptimal solutions.

  • error

    Not recognizing that XOR can efficiently solve the problem in O(1) space.

  • error

    Overcomplicating the solution with unnecessary steps when a simple hash table or XOR solution suffices.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    The problem could involve finding the missing character from a set of strings, rather than two strings.

  • arrow_right_alt

    An extension could involve multiple additional characters being added to t, increasing the complexity.

  • arrow_right_alt

    Consider a scenario where both strings are very large, testing the scalability of different approaches.

help

常见问题

外企场景

找不同题解:哈希·表·结合·string | LeetCode #389 简单