LeetCode 题解工作台
字符串中最大的 3 位相同数字
给你一个字符串 num ,表示一个大整数。如果一个整数满足下述所有条件,则认为该整数是一个 优质整数 : 该整数是 num 的一个长度为 3 的 子字符串 。 该整数由唯一一个数字重复 3 次组成。 以字符串形式返回 最大的优质整数 。如果不存在满足要求的整数,则返回一个空字符串 "" 。 注意: …
1
题型
5
代码语言
3
相关题
当前训练重点
简单 · String-driven solution strategy
答案摘要
我们可以从大到小枚举每个数字 ,其中 $0 \le i \le 9$,然后判断连续的三个 构成的字符串 是否是 的子串,若是,直接返回 即可。 若枚举完所有的 都没有找到满足条件的字符串,则返回空字符串。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路
题目描述
给你一个字符串 num ,表示一个大整数。如果一个整数满足下述所有条件,则认为该整数是一个 优质整数 :
- 该整数是
num的一个长度为3的 子字符串 。 - 该整数由唯一一个数字重复
3次组成。
以字符串形式返回 最大的优质整数 。如果不存在满足要求的整数,则返回一个空字符串 "" 。
注意:
- 子字符串 是字符串中的一个连续字符序列。
num或优质整数中可能存在 前导零 。
示例 1:
输入:num = "6777133339" 输出:"777" 解释:num 中存在两个优质整数:"777" 和 "333" 。 "777" 是最大的那个,所以返回 "777" 。
示例 2:
输入:num = "2300019" 输出:"000" 解释:"000" 是唯一一个优质整数。
示例 3:
输入:num = "42352338" 输出:"" 解释:不存在长度为 3 且仅由一个唯一数字组成的整数。因此,不存在优质整数。
提示:
3 <= num.length <= 1000num仅由数字(0-9)组成
解题思路
方法一:枚举
我们可以从大到小枚举每个数字 ,其中 ,然后判断连续的三个 构成的字符串 是否是 的子串,若是,直接返回 即可。
若枚举完所有的 都没有找到满足条件的字符串,则返回空字符串。
时间复杂度 ,其中 是字符串 的长度。空间复杂度 。
class Solution:
def largestGoodInteger(self, num: str) -> str:
for i in range(9, -1, -1):
if (s := str(i) * 3) in num:
return s
return ""
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Look for understanding of string manipulation and optimization in checking sequences.
- question_mark
Evaluate the candidate's ability to leverage built-in functions for efficiency.
- question_mark
Check if they correctly handle edge cases, such as strings with no valid good integers.
常见陷阱
外企场景- error
Failing to check for the sequences in the correct order, leading to inefficient or incorrect results.
- error
Not handling strings with no valid good integers correctly, potentially returning incorrect results.
- error
Misunderstanding the problem's constraints and overcomplicating the solution.
进阶变体
外企场景- arrow_right_alt
What if the string contains more than one valid good integer? The problem only requires returning the largest one.
- arrow_right_alt
What if the string has repeated 3-digit sequences? Ensure to return the first largest found.
- arrow_right_alt
What if the string contains only one or two digits? The output should be an empty string as no valid good integer can exist.