JAVA easy to understand + explanation


  • 2
    M

    Digits are uniquely identified by their letters as follows: first we eliminate the numbers zero, two, four, six, eight which are uniquely identified by their bolded character from all the possible digit strings. Next we eliminate all occurences of digits: one, three, five cause out of the remaining digits these are uniquely identified by their respective bold characters. Lastly we are left with nine and seven which are again identified by their i and v respectively.

    void getDigitByChar(char c, String digitString, int digit,  HashMap<Character,Integer> hm, List<Integer> ret)
    {
        if(hm.containsKey(c)){
            int nr=hm.get(c);
            for(char x : digitString.toCharArray()){
                hm.put(x, hm.get(x)-nr);
                if(hm.get(x)==0) hm.remove(x);
            }
             while(nr>0){
                 ret.add(digit); 
                 nr--;
             }
        }
    }
    
    public String originalDigits(String s) 
    {
        List<Integer> ret = new LinkedList<Integer>();
        HashMap<Character,Integer> hm = new HashMap<Character,Integer>();
        for(char c : s.toCharArray()){
            if(!hm.containsKey(c)) hm.put(c,0);
            hm.put(c,hm.get(c)+1);
        }
        getDigitByChar('z',"zero",0,hm,ret);
        getDigitByChar('w',"two",2,hm,ret);
        getDigitByChar('u',"four",4,hm,ret);
        getDigitByChar('x',"six",6,hm,ret);
        getDigitByChar('g',"eight",8,hm,ret);
        getDigitByChar('o',"one",1,hm,ret);
        getDigitByChar('h',"three",3,hm,ret);
        getDigitByChar('f',"five",5,hm,ret);
        getDigitByChar('v',"seven",7,hm,ret);
        getDigitByChar('i',"nine",9,hm,ret);
    
        Collections.sort(ret);
        String result="";
        for(int x: ret) result+=x;
        
        return result;
    }

Log in to reply
 

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