Jave find unique char in each number and remove


  • 2
    public class Solution {
        public String originalDigits(String s) {
            int[] frequency = new int[26];
            for (char c : s.toCharArray()) {
                frequency[c - 'a']++;
            }
            List<Character> list = new ArrayList<>();
            removeDigit('z', '0', "zero", list, frequency);
            removeDigit('w', '2', "two", list, frequency);
            removeDigit('u', '4', "four", list, frequency);
            removeDigit('x', '6', "six", list, frequency);
            removeDigit('g', '8', "eight", list, frequency);
            removeDigit('o', '1', "one", list, frequency);
            removeDigit('h', '3', "three", list, frequency);
            removeDigit('f', '5', "five", list, frequency);
            removeDigit('s', '7', "seven", list, frequency);
            removeDigit('n', '9', "nine", list, frequency);
            
            Collections.sort(list);
            StringBuilder result = new StringBuilder();
            for (char c : list) {
                result.append(c);
            }
            return new String(result);
        }
        
        private void removeDigit(char symbol, char digit, String number, List<Character> list, int[] frequency) {
            while (frequency[symbol - 'a'] > 0) {
                list.add(digit);
                for (char c : number.toCharArray()) {
                    frequency[c - 'a']--;
                }
            }
        }
    }
    

Log in to reply
 

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