Leetcode——从英文中重建数字

Posted Yawn__

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode——从英文中重建数字相关的知识,希望对你有一定的参考价值。

1. 从英文中重建数字

2 题解

首先我们可以统计每个字母分别在哪些数字中出现:

然后根据「英文单词中的字符唯一性」确定构建的顺序,最后再对答案进行排序即可。

  • zero 中的 z 在其余所有单词中都没出现过,我们可以先统计 zero 的出现次数,并构建 0;
  • 然后观察剩余数字,其中 eight 中的 g 具有唯一性,构建 8;
  • 再发现 six 中的 x 具有唯一性,构建 6;
  • 发现 three 中的 h 具有唯一性(利用在此之前 eight 已经被删除干净,词频中仅存在 three 对应的 h),构建 3 …

最终可以确定一个可行的构建序列为 0, 8, 6, 3, 2, 7, 5, 9, 4, 1。

class Solution 
    static String[] ss = new String[]"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine";
    static int[] priority = new int[] 0, 8, 6, 3, 2, 7, 5, 9, 4, 1;
    public String originalDigits(String s) 
        int n = s.length();
        int[] cnts = new int[26];
        for (int i = 0; i < n; i++) cnts[s.charAt(i) - 'a']++;
        StringBuilder sb = new StringBuilder();
        for (int i : priority) 
            int k = Integer.MAX_VALUE;
            for (char c : ss[i].toCharArray()) k = Math.min(k, cnts[c - 'a']);
            for (char c : ss[i].toCharArray()) cnts[c - 'a'] -= k;
            while (k-- > 0) sb.append(i);
        
        char[] cs = sb.toString().toCharArray();
        Arrays.sort(cs);
        return String.valueOf(cs);
    

以上是关于Leetcode——从英文中重建数字的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode——从英文中重建数字

leetcode每日一题-423:从英文中重建数字

《LeetCode之每日一题》:218.从英文中重建数字

LeetCode 423 从英文中重建数字[数组] HERODING的LeetCode之路

[LeetCode] Reconstruct Original Digits from English 从英文中重建数字

Leetcode-423 Reconstruct Original Digits from English(从英文中重建数字)