目录

0423:从英文中重建数字(★)

力扣第 423 题

题目

给你一个字符串 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 保证是一个符合题目要求的字符串

分析

  • 可以假设每个数字的个数,得到一个联立方程组,求解即可
  • 例如只有 ‘0’ 的英文里含有 ‘z’ 字母,故 ‘z’ 的个数即是原本 ‘0’ 的个数

解答

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
    def originalDigits(self, s: str) -> str:
        ct = Counter(s)
        A = [0]*10
        A[0] = ct['z']
        A[2] = ct['w']
        A[4] = ct['u']
        A[6] = ct['x']
        A[8] = ct['g']
        A[1] = ct['o']-A[0]-A[2]-A[4]
        A[3] = ct['t']-A[2]-A[8]
        A[5] = ct['f']-A[4]
        A[7] = ct['s']-A[6]
        A[9] = ct['i']-A[5]-A[6]-A[8]
        return ''.join(str(i)*a for i,a in enumerate(A))

561ms