LeetCode 题解工作台
找不同
给定两个字符串 s 和 t ,它们只包含小写字母。 字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。 请找出在 t 中被添加的字母。 示例 1: 输入: s = "abcd", t = "abcde" 输出: "e" 解释: 'e' 是那个被添加的字母。 示例 2: 输入: s = …
4
题型
7
代码语言
3
相关题
当前训练重点
简单 · 哈希·表·结合·string
答案摘要
我们可以用一个哈希表或数组 统计字符串 中每个字符出现的次数,再遍历字符串 ,对于每个字符,我们在 中减去一次出现的次数,如果对应次数为负数,则说明该字符在 中出现的次数大于在 中出现的次数,因此该字符为被添加的字符。 时间复杂度 ,空间复杂度 ,其中 为字符串的长度,而 表示字符集,这里字符集为所有小写字母,所以 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路
题目描述
给定两个字符串 s 和 t ,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
示例 1:
输入:s = "abcd", t = "abcde" 输出:"e" 解释:'e' 是那个被添加的字母。
示例 2:
输入:s = "", t = "y" 输出:"y"
提示:
0 <= s.length <= 1000t.length == s.length + 1s和t只包含小写字母
解题思路
方法一:计数
我们可以用一个哈希表或数组 统计字符串 中每个字符出现的次数,再遍历字符串 ,对于每个字符,我们在 中减去一次出现的次数,如果对应次数为负数,则说明该字符在 中出现的次数大于在 中出现的次数,因此该字符为被添加的字符。
时间复杂度 ,空间复杂度 ,其中 为字符串的长度,而 表示字符集,这里字符集为所有小写字母,所以 。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.