Observe the pattern, concise java code

  • 0

    My solution is not the best on all posts, just try to share my thinking process

    public class Solution {
        public String originalDigits(String s) {
            String[] dict = new String[]{"zero","one","two","three","four","five","six","seven","eight","nine"};
            int[] index = new int[]{0,6,7,5,2,4,3,1,8,9};
            int[] result = new int[10];
            int[] map = new int[26];
            for(char a: s.toCharArray()) map[a-'a']++;
            StringBuilder res = new StringBuilder();
            for(int i =0;i<10  ;i++){
                int cur = index[i];
                String temp = dict[cur];
                int min= Integer.MAX_VALUE;
                for(char a: temp.toCharArray()) min = Math.min(min,map[a-'a']);
                for(char a: temp.toCharArray()) {map[a-'a'] = map[a-'a']-min;}
                result[cur] = min;
            for(int i =0 ;i<result.length;i++) {
                while(result[i]-->0) res.append(String.valueOf(i));
            return res.toString();

    I mainly wanna explain index array part
    0:First we start to count how many zero are in the String since character "z" is unique from one to ten
    6:same apply to six where character "x" is unique
    7:after exclude 6 ,we find that char "s" in seven is unique
    5: after exclude 7, we find that char "v" is unique in five
    2: char "w" in unique in two, you can put 2 in the front, does not matter
    4: after exclude five, char "f" is unique in four
    3: after exclude two, we find char "t" is unique in three
    1: "o" is unique in one
    8: "h" is unique in eight
    then 9

    rest of the code, I think is pretty straightforward

    for index array, there are other combination, you may try yourself

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.