Given a non-empty string containing an out-of-order English representation of digits 0-9
, output the digits in ascending order.
Note:
- Input contains only lowercase English letters.
- Input is guaranteed to be valid and can be transformed to its original digits. That means invalid inputs such as "abc" or "zerone" are not permitted.
- Input length is less than 50,000.
Example 1:
Input: "owoztneoer" Output: "012"
Example 2:
Input: "fviefuro" Output: "45"
根据每个数中英文字母的特殊性,统计数的个数,最后遍历打印。代码如下:
public class Solution {
public String originalDigits(String s) {
int[] count = new int[10];
for (char ch: s.toCharArray()){
if(ch == 'z') count[0]++;
else if (ch == 'o') count[1]++;
else if (ch == 'w') count[2]++;
else if (ch == 'r') count[3]++;
else if (ch == 'u') count[4]++;
else if (ch == 'f') count[5]++;
else if (ch == 'x') count[6]++;
else if (ch == 's') count[7]++;
else if (ch == 'g') count[8]++;
else if (ch == 'i') count[9]++;
}
count[1] = count[1] - count[0] - count[2] - count[4];
count[3] = count[3] - count[0] - count[4];
count[5] = count[5] - count[4];
count[7] = count[7] - count[6];
count[9] = count[9] - count[8] - count[6] - count[5];
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i ++) {
for (int j = 0; j < count[i]; j ++) {
sb.append(i);
}
}
return sb.toString();
}
}