LeetCode 题解工作台

从英文中重建数字

给你一个字符串 s ,其中包含字母顺序打乱的用英文单词表示的若干数字( 0-9 )。按 升序 返回原始的数字。 示例 1: 输入: s = "owoztneoer" 输出: "012" 示例 2: 输入: s = "fviefuro" 输出: "45" 提示: 1 5 s[i] 为 ["e","g"…

category

3

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

中等 · 哈希·数学

bolt

答案摘要

class Solution: def originalDigits(self, s: str) -> str:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 哈希·数学 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 s ,其中包含字母顺序打乱的用英文单词表示的若干数字(0-9)。按 升序 返回原始的数字。

 

示例 1:

输入:s = "owoztneoer"
输出:"012"

示例 2:

输入:s = "fviefuro"
输出:"45"

 

提示:

  • 1 <= s.length <= 105
  • s[i]["e","g","f","i","h","o","n","s","r","u","t","w","v","x","z"] 这些字符之一
  • s 保证是一个符合题目要求的字符串
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
    def originalDigits(self, s: str) -> str:
        counter = Counter(s)
        cnt = [0] * 10

        cnt[0] = counter['z']
        cnt[2] = counter['w']
        cnt[4] = counter['u']
        cnt[6] = counter['x']
        cnt[8] = counter['g']

        cnt[3] = counter['h'] - cnt[8]
        cnt[5] = counter['f'] - cnt[4]
        cnt[7] = counter['s'] - cnt[6]

        cnt[1] = counter['o'] - cnt[0] - cnt[2] - cnt[4]
        cnt[9] = counter['i'] - cnt[5] - cnt[6] - cnt[8]

        return ''.join(cnt[i] * str(i) for i in range(10))
speed

复杂度分析

指标
时间complexity is O(n) where n is the length of the input string, dominated by single-pass counting and deductions. Space complexity is O(1) since the hash table size is fixed at 26 letters and digit counts are constant.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Asks if you can optimize letter counting rather than trying all permutations of words.

  • question_mark

    Wants you to identify unique characters that map directly to digits before resolving overlaps.

  • question_mark

    Checks if you can handle edge cases where multiple digits share letters, like 'one' and 'nine'.

warning

常见陷阱

外企场景
  • error

    Failing to deduct overlapping letters after counting unique digits leads to incorrect counts.

  • error

    Sorting the final digits incorrectly or omitting digits present multiple times.

  • error

    Assuming all letters are unique to one digit without checking overlaps, which causes errors.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Input strings with repeated digit words appearing multiple times, testing counting accuracy.

  • arrow_right_alt

    Strings missing some digits entirely, requiring robust handling of zeros in counts.

  • arrow_right_alt

    Extended character sets with additional noise letters not part of digit words, testing filtering.

help

常见问题

外企场景

从英文中重建数字题解:哈希·数学 | LeetCode #423 中等