LeetCode 题解工作台

字符串中第二大的数字

给你一个混合字符串 s ,请你返回 s 中 第二大 的数字,如果不存在第二大的数字,请你返回 -1 。 混合字符串 由小写英文字母和数字组成。 示例 1: 输入: s = "dfa12321afd" 输出: 2 解释: 出现在 s 中的数字包括 [1, 2, 3] 。第二大的数字是 2 。 示例 2…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 哈希·表·结合·string

bolt

答案摘要

我们定义 和 分别表示字符串中出现的最大数字和第二大数字,初始时 $a = b = -1$。 遍历字符串 ,如果当前字符是数字,我们将其转换为数字 ,如果 $v \gt a$,说明 是当前出现的最大数字,我们将 更新为 ,并将 更新为 ;如果 $v \lt a$,说明 是当前出现的第二大数字,我们将 更新为 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个混合字符串 s ,请你返回 s 中 第二大 的数字,如果不存在第二大的数字,请你返回 -1 。

混合字符串 由小写英文字母和数字组成。

 

示例 1:

输入:s = "dfa12321afd"
输出:2
解释:出现在 s 中的数字包括 [1, 2, 3] 。第二大的数字是 2 。

示例 2:

输入:s = "abc1111"
输出:-1
解释:出现在 s 中的数字只包含 [1] 。没有第二大的数字。

 

提示:

  • 1 <= s.length <= 500
  • s 只包含小写英文字母和(或)数字。
lightbulb

解题思路

方法一:一次遍历

我们定义 aabb 分别表示字符串中出现的最大数字和第二大数字,初始时 a=b=1a = b = -1

遍历字符串 ss,如果当前字符是数字,我们将其转换为数字 vv,如果 v>av \gt a,说明 vv 是当前出现的最大数字,我们将 bb 更新为 aa,并将 aa 更新为 vv;如果 v<av \lt a,说明 vv 是当前出现的第二大数字,我们将 bb 更新为 vv

遍历结束,返回 bb 即可。

时间复杂度 O(n)O(n),其中 nn 为字符串 ss 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

字符串中第二大的数字题解:哈希·表·结合·string | LeetCode #1796 简单