用到的知识
集合排序
//对数字进行排序List<Integer> nums = Arrays.asList(3,1,5,2,9,8,4,10,6,7);nums.sort(Comparator.reverseOrder()); //reverseOrder倒序System.err.println("倒序:"+nums);nums.sort(Comparator.naturalOrder()); //naturalOrder自然排序即:正序System.err.println("正序:"+nums);
解题代码
class Solution { public String originalDigits(String s) { /** * 0: zero z * 1: one * 2: two w * 3: three * 4: four u * 5: five * 6: six x * 7: seven * 8: eight g * 9: nine * * g,u, w,x,z * * zero,two,four, six ,eight, * * one,three,five,seven, * r,s,f,o */ char[] chars = s.toCharArray(); Map<Character,Integer> map = new HashMap<>(); for (char c: chars ) { map.put(c,map.getOrDefault(c,0) + 1); } //除去只出现一次的数字 List<Integer> l = new ArrayList<>(); if(map.containsKey('z')) { addList('z',map,0,l,"zero"); } if(map.containsKey('w')) { addList('w',map,2,l,"two"); } if(map.containsKey('u')) { addList('u',map,4,l,"four"); } if(map.containsKey('x')) { addList('x',map,6,l,"six"); } if(map.containsKey('g')) { addList('g',map,8,l,"eight"); } /** * one,three,five,seven, * * r,s,f,o */ //排除上述 数字,除去只出现一次的数字 if(map.containsKey('o')) { addList('o',map,1,l,"one"); } if(map.containsKey('r')) { addList('r',map,3,l,"three"); } if(map.containsKey('f')) { addList('f',map,5,l,"five"); } if(map.containsKey('s')) { addList('s',map,7,l,"seven"); } //nine 统计i或者e的个数 if(map.containsKey('i')) { addList('i',map,9,l,"nine"); } l.sort(Comparator.naturalOrder()); String result = l.stream().map( t -> String.valueOf(t)).collect(Collectors.joining("")); return result; } public void addList(char c,Map<Character,Integer> map,int num, List<Integer> l,String s) { int len = map.get(c); //统计出现次数 for(int i = 0; i < len ; i++ ) { l.add(num); //加入集合 } char[] chars = s.toCharArray(); for (int i = 0; i < chars.length; i++) { int value = map.get(chars[i])- len; if(value == 0) { //为0删除char map.remove(chars[i]); } else { map.put(chars[i], value ) ; //更新字符出现次数 } } }}