LeetCode 题解工作台
字符串中第二大的数字
给你一个混合字符串 s ,请你返回 s 中 第二大 的数字,如果不存在第二大的数字,请你返回 -1 。 混合字符串 由小写英文字母和数字组成。 示例 1: 输入: s = "dfa12321afd" 输出: 2 解释: 出现在 s 中的数字包括 [1, 2, 3] 。第二大的数字是 2 。 示例 2…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 哈希·表·结合·string
答案摘要
我们定义 和 分别表示字符串中出现的最大数字和第二大数字,初始时 $a = b = -1$。 遍历字符串 ,如果当前字符是数字,我们将其转换为数字 ,如果 $v \gt a$,说明 是当前出现的最大数字,我们将 更新为 ,并将 更新为 ;如果 $v \lt a$,说明 是当前出现的第二大数字,我们将 更新为 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路
题目描述
给你一个混合字符串 s ,请你返回 s 中 第二大 的数字,如果不存在第二大的数字,请你返回 -1 。
混合字符串 由小写英文字母和数字组成。
示例 1:
输入:s = "dfa12321afd" 输出:2 解释:出现在 s 中的数字包括 [1, 2, 3] 。第二大的数字是 2 。
示例 2:
输入:s = "abc1111" 输出:-1 解释:出现在 s 中的数字只包含 [1] 。没有第二大的数字。
提示:
1 <= s.length <= 500s只包含小写英文字母和(或)数字。
解题思路
方法一:一次遍历
我们定义 和 分别表示字符串中出现的最大数字和第二大数字,初始时 。
遍历字符串 ,如果当前字符是数字,我们将其转换为数字 ,如果 ,说明 是当前出现的最大数字,我们将 更新为 ,并将 更新为 ;如果 ,说明 是当前出现的第二大数字,我们将 更新为 。
遍历结束,返回 即可。
时间复杂度 ,其中 为字符串 的长度。空间复杂度 。
class Solution:
def secondHighest(self, s: str) -> int:
a = b = -1
for c in s:
if c.isdigit():
v = int(c)
if v > a:
a, b = v, a
elif b < v < a:
b = v
return b
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for a solution that efficiently handles string parsing and digit extraction.
- question_mark
Ensure the candidate considers edge cases such as no digits or only one digit.
- question_mark
Expect a clear understanding of hash tables for removing duplicates and sorting for the second largest value.
常见陷阱
外企场景- error
Failing to handle cases with fewer than two digits correctly.
- error
Not accounting for the presence of non-digit characters in the string.
- error
Incorrectly assuming there will always be at least two distinct digits.
进阶变体
外企场景- arrow_right_alt
What if the string contains non-digit characters only? How should the program behave?
- arrow_right_alt
Consider the situation where there are multiple occurrences of the largest digit, but no second largest.
- arrow_right_alt
What if the string has exactly two distinct digits? Ensure the program still returns the second largest.