LeetCode 题解工作台
检查相同字母间的距离
给你一个下标从 0 开始的字符串 s ,该字符串仅由小写英文字母组成, s 中的每个字母都 恰好 出现 两次 。另给你一个下标从 0 开始、长度为 26 的的整数数组 distance 。 字母表中的每个字母按从 0 到 25 依次编号(即, 'a' -> 0 , 'b' -> 1 , 'c' ->…
3
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们可以用哈希表 记录每个字母出现的下标,然后遍历哈希表,判断每个字母的下标之差是否等于 `distance` 中对应的值。如果出现不等的情况,直接返回 `false`。如果遍历结束后,没有出现不等的情况,返回 `true`。 时间复杂度 ,其中 为字符串 的长度。空间复杂度 ,其中 为字符集,这里为小写字母集合。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个下标从 0 开始的字符串 s ,该字符串仅由小写英文字母组成,s 中的每个字母都 恰好 出现 两次 。另给你一个下标从 0 开始、长度为 26 的的整数数组 distance 。
字母表中的每个字母按从 0 到 25 依次编号(即,'a' -> 0, 'b' -> 1, 'c' -> 2, ... , 'z' -> 25)。
在一个 匀整 字符串中,第 i 个字母的两次出现之间的字母数量是 distance[i] 。如果第 i 个字母没有在 s 中出现,那么 distance[i] 可以 忽略 。
如果 s 是一个 匀整 字符串,返回 true ;否则,返回 false 。
示例 1:
输入:s = "abaccb", distance = [1,3,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] 输出:true 解释: - 'a' 在下标 0 和下标 2 处出现,所以满足 distance[0] = 1 。 - 'b' 在下标 1 和下标 5 处出现,所以满足 distance[1] = 3 。 - 'c' 在下标 3 和下标 4 处出现,所以满足 distance[2] = 0 。 注意 distance[3] = 5 ,但是由于 'd' 没有在 s 中出现,可以忽略。 因为 s 是一个匀整字符串,返回 true 。
示例 2:
输入:s = "aa", distance = [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] 输出:false 解释: - 'a' 在下标 0 和 1 处出现,所以两次出现之间的字母数量为 0 。 但是 distance[0] = 1 ,s 不是一个匀整字符串。
提示:
2 <= s.length <= 52s仅由小写英文字母组成s中的每个字母恰好出现两次distance.length == 260 <= distance[i] <= 50
解题思路
方法一:数组或哈希表
我们可以用哈希表 记录每个字母出现的下标,然后遍历哈希表,判断每个字母的下标之差是否等于 distance 中对应的值。如果出现不等的情况,直接返回 false。如果遍历结束后,没有出现不等的情况,返回 true。
时间复杂度 ,其中 为字符串 的长度。空间复杂度 ,其中 为字符集,这里为小写字母集合。
class Solution:
def checkDistances(self, s: str, distance: List[int]) -> bool:
d = defaultdict(int)
for i, c in enumerate(map(ord, s), 1):
j = c - ord("a")
if d[j] and i - d[j] - 1 != distance[j]:
return False
d[j] = i
return True
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) where n is the length of s, as each character is visited once. Space complexity is O(1) because the fixed-size array of 26 letters is used regardless of input size. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Looking for correct use of a fixed-size hash or array to track first occurrences
- question_mark
Expecting early termination upon detecting a distance mismatch
- question_mark
Confirming understanding of converting letters to array indices for distance lookup
常见陷阱
外企场景- error
Forgetting to subtract indices correctly to count letters between occurrences
- error
Not handling letters that do not appear in s correctly
- error
Reinitializing tracking array inside the loop causing incorrect first occurrence tracking
进阶变体
外企场景- arrow_right_alt
Letters may appear more than twice and distance rules may apply to first and last occurrences only
- arrow_right_alt
Distance array may contain -1 to indicate letters that can be ignored
- arrow_right_alt
Input string could include uppercase letters requiring normalization before indexing