题意:
将无序的英文字母对应的数字还原为阿拉伯数字并升序输出
分析:
我们现在分解简化问题,那么我们不排序,只需要找出是那些数字。
zero:0 z可唯一标识
one:1
two:2 w可唯一标识
three:3
four:4 u可唯一标识
five:5
six:6 x可唯一标识
seven:7
eight:8 g可唯一标识
nine:9
因为是无序的,也不可能还原出顺序,我们关注的点只能是每种有多少个,考虑用map,然后取出比如z的个数然后删除ero。完成代码之后看讨论区,才发现自己真是何必这么麻烦。
其一,使用map的时候,考虑能不能用数组代替,这里显然是可以的。
其二,删除的时候,考虑能不能不删除,这样的话,就不能唯一判断了,那么比如判断five之后不删除fie,那么f就不能唯一判断4,那么f的个数就等于4和55的个数之和,我们可以采取相减的办法。所以,一个操作麻烦的时候,注意去思考是否必要和代替的方案。
参考改进之后的代码:
public class Solution { public String originalDigits(String s) { int[] count = new int[10]; for (int i = 0; i < s.length(); i++){ char c = s.charAt(i); if (c == 'z') count[0]++; if (c == 'w') count[2]++; if (c == 'u') count[4]++; if (c == 'x') count[6]++; if (c == 'g') count[8]++; if (c == 'f') count[5]++; //5,4 //5在后面要用到,下面减的时候要在前面 if (c == 'v') count[7]++; //7,5 if (c == 'h') count[3]++; //3,8 if (c == 'i') count[9]++; //9,8,5,6 if (c == 'o') count[1]++; //1,0,2,4 } count[5] = count[5] - count[4]; //5先减 count[7] = count[7] - count[5]; count[3] = count[3] - count[8]; count[9] = count[9] - count[8] - count[5] - count[6]; count[1] = count[1] - count[0] - count[2] - count[4]; StringBuilder sb = new StringBuilder(); for (int i = 0; i <= 9; i++){ for (int j = 0; j < count[i]; j++){ sb.append(i); } } return sb.toString(); } }