LeetCode 题解工作台
找到字符串中合法的相邻数字
给你一个只包含数字的字符串 s 。如果 s 中两个 相邻 的数字满足以下条件,我们称它们是 合法的 : 前面的数字 不等于 第二个数字。 两个数字在 s 中出现的次数 恰好 分别等于这个数字本身。 请你从左到右遍历字符串 s ,并返回最先找到的 合法 相邻数字。如果这样的相邻数字不存在,请你返回一个…
3
题型
5
代码语言
3
相关题
当前训练重点
简单 · 哈希·表·结合·string
答案摘要
我们可以用一个长度为 的数组 记录字符串 中每个数字出现的次数。 然后我们遍历字符串 中的相邻数字对,如果这两个数字不相等且满足这两个数字出现的次数分别等于这两个数字本身,我们就找到了一个合法的相邻数字对,返回即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路
题目描述
给你一个只包含数字的字符串 s 。如果 s 中两个 相邻 的数字满足以下条件,我们称它们是 合法的 :
- 前面的数字 不等于 第二个数字。
- 两个数字在
s中出现的次数 恰好 分别等于这个数字本身。
请你从左到右遍历字符串 s ,并返回最先找到的 合法 相邻数字。如果这样的相邻数字不存在,请你返回一个空字符串。
示例 1:
输入:s = "2523533"
输出:"23"
解释:
数字 '2' 出现 2 次,数字 '3' 出现 3 次。"23" 中每个数字在 s 中出现的次数都恰好分别等于数字本身。所以输出 "23" 。
示例 2:
输入:s = "221"
输出:"21"
解释:
数字 '2' 出现 2 次,数字 '1' 出现 1 次。所以输出 "21" 。
示例 3:
输入:s = "22"
输出:""
解释:
没有合法的相邻数字。
提示:
2 <= s.length <= 100s只包含'1'到'9'的数字。
解题思路
方法一:计数
我们可以用一个长度为 的数组 记录字符串 中每个数字出现的次数。
然后我们遍历字符串 中的相邻数字对,如果这两个数字不相等且满足这两个数字出现的次数分别等于这两个数字本身,我们就找到了一个合法的相邻数字对,返回即可。
遍历结束后,如果没有找到合法的相邻数字对,我们返回一个空字符串。
时间复杂度 ,其中 为字符串 的长度。空间复杂度 ,其中 为字符串 中出现的字符集,本题中 。
class Solution:
def findValidPair(self, s: str) -> str:
cnt = [0] * 10
for x in map(int, s):
cnt[x] += 1
for x, y in pairwise(map(int, s)):
if x != y and cnt[x] == x and cnt[y] == y:
return f"{x}{y}"
return ""
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) for counting plus O(n) for scanning adjacent pairs, yielding overall O(n). Space complexity is O(1) since the hash table only stores counts for digits '1' through '9'. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Does the candidate correctly handle counting digit occurrences with a hash table?
- question_mark
Does the candidate correctly check every adjacent pair without skipping potential valid pairs?
- question_mark
Is the solution efficient in both time and space considering the small fixed digit set?
常见陷阱
外企场景- error
Ignoring that only digits '1' through '9' are valid and counting '0' can lead to errors.
- error
Failing to return the first valid pair and instead returning the last or all pairs.
- error
Recomputing counts for each pair instead of precomputing frequencies using a hash table.
进阶变体
外企场景- arrow_right_alt
Find all valid adjacent pairs instead of just the first one.
- arrow_right_alt
Allow the string to include '0' and adjust the counting condition accordingly.
- arrow_right_alt
Find valid triplets of digits where each digit's frequency equals its numeric value.