Loading

423. [字符串]从英文中重建数字

423. 从英文中重建数字

第一次看到到题目时,其实我们的可能没什么思路,不妨观察下列数字:

数字 英文
0 zero
2 two
4 four
6 six
8 eight

这些数字对应的英文单词中有一个有别于其他数字的字母,我们可以通过这些字符出现的次数,计算出这些数字出现的次数,那么剩下的数字怎么办?我们可以利用已经计算出来的数字做一些推理。

数字 英文 计算规则
1 one ”o”出现的次数-“zero”出现的次数-“two”出现的次数-"four"出现的次数
3 three ”h“出现的次数-”eight“出现的次数
5 five ”f“出现的次数-”four“出现的次数
7 seven "v"出现的次数-”five“出现的次数
9 nine “i”出现的次数-“five”出现的次数-“eight”出现的次数
// 执行用时: 5 ms , 在所有 Java 提交中击败了 65.94% 的用户 
// 内存消耗: 39.8 MB , 在所有 Java 提交中击败了 21.83% 的用户
class Solution {
    public String originalDigits(String s) {
        int[] words = new int[26];
        //先统计一下所有字母的个数
        for(char a : s.toCharArray()){
            words[a - 'a']++;
        }
        int[] nums = new int[10];
        nums[0] = words[25];  // 'z' - 'a'
        nums[2] = words[22];  // 'w' - 'a'
        nums[4] = words[20];  // 'u' - 'a'
        nums[6] = words[23];  // 'x' - 'a'
        nums[8] = words[6];  // 'g' - 'a'
        nums[5] = words[5] - nums[4];  // 'f' - 'a'
        nums[7] = words[21] - nums[5];  // 'v' - 'a' 
        nums[3] = words[7] - nums[8];  // 'h' - 'a'
        nums[9] = words[8] - nums[5] - nums[6] - nums[8];  // 'i' - 'a'
        nums[1] = words[14] - nums[0] - nums[2] - nums[4];  // 'o' - 'a'
        StringBuffer str = new StringBuffer();  
        for(int i = 0; i < nums.length; i++){
            while(nums[i]-- > 0){
                str.append(i);
            }
        }
        return str.toString();
    }
}
posted @ 2020-10-24 12:19  上海井盖王  阅读(149)  评论(0)    收藏  举报