🌕🌕 423. 从英文中重建数字

吞佛童子2022年10月10日
  • algorithm
  • 找规律
大约 1 分钟

🌕🌕 423. 从英文中重建数字

难度: 🌕🌕

问题描述

img_7.png


解法

class Solution {
    public String originalDigits(String s) {
        // 思路:
        // 找规律
        // 某个字符只要出现,那么就可以唯一确定某个值
        // {0, 2, 4, 6, 8} 均是此类情况
        // 排除了以上数字之后,本来非唯一性的值就可以由剩下的字符确定唯一性
        // 剩下的值的一个可以存在的顺序为:{3, 5, 7, 9, 1}
        int[] arr = new int[26];
        for(char c:s.toCharArray()) {
            int index = c - 'a';
            arr[index] ++;
        }
        // 按照上述规律依次判断
        int[] res = new int[10]; // 记录 0 - 9 各自出现的次数
        res[0] = arr['z' - 'a']; // zero 由 z 唯一性确定
        res[2] = arr['w' - 'a']; // two -- w
        res[4] = arr['u' - 'a']; // four -- u
        res[6] = arr['x' - 'a']; // six -- x
        res[8] = arr['g' - 'a']; // eight -- g

        res[3] = arr['h' - 'a'] - res[8]; // three & eight -- h
        res[5] = arr['f' - 'a'] - res[4]; // five & four -- f
        res[7] = arr['s' - 'a'] - res[6]; // seven & six -- s
        res[9] = arr['i' - 'a'] - res[5] - res[6] - res[8]; // nine & five & six & eight -- i
        res[1] = arr['o' - 'a'] - res[0] - res[2] - res[4]; // one & zero & four -- o

        // 组装结果
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < res.length; i ++) {
            if(res[i] == 0) {
                continue;
            }
            // res[i] > 0
            for(int j = 0; j < res[i]; j ++) {
                sb.append(i);
            }
        }
        return sb.toString();
    }
}

输出

img_6.png

上次编辑于: 2022/10/10 下午8:43:48
贡献者: liuxianzhishou