题意
给你字符串,保证这些字符串能组合成0-9的英文单词,如zero,one,two...,请你按顺序输出这些数字,如ezowrte,能组合成zero,two,那就输出02
解答
我发现zero,one,two...nine,在这些单词里,有些字母是只出现在一个单词里的,比如z出现在zero,那么我就能通过z来得到zero出现的次数,所以我就统计所有字母出现的次数来计算每个单词出现次数
public class Solution {
public String originalDigits(String s) {
StringBuilder sb = new StringBuilder();
int[] cnt = new int[26];
int[] num = new int[10];
for (int i = 0; i < s.length(); i++) {
cnt[s.charAt(i)-'a']++;
}
int x;
// zero
x = cnt['z'-'a'];
num[0] = x;
cnt['z'-'a'] -= x;
cnt['e'-'a'] -= x;
cnt['r'-'a'] -= x;
cnt['o'-'a'] -= x;
// two
x = cnt['w'-'a'];
num[2] = x;
cnt['t'-'a'] -= x;
cnt['w'-'a'] -= x;
cnt['o'-'a'] -= x;
// four
x = cnt['u'-'a'];
num[4] = x;
cnt['f'-'a'] -= x;
cnt['o'-'a'] -= x;
cnt['u'-'a'] -= x;
cnt['r'-'a'] -= x;
// six
x = cnt['x'-'a'];
num[6] = x;
cnt['s'-'a'] -= x;
cnt['i'-'a'] -= x;
cnt['x'-'a'] -= x;
// one
x = cnt['o'-'a'];
num[1] = x;
cnt['o'-'a'] -= x;
cnt['n'-'a'] -= x;
cnt['e'-'a'] -= x;
// three
x = cnt['r'-'a'];
num[3] = x;
cnt['t'-'a'] -= x;
cnt['h'-'a'] -= x;
cnt['r'-'a'] -= x;
cnt['e'-'a'] -= x;
cnt['e'-'a'] -= x;
// five
x = cnt['f'-'a'];
num[5] = x;
cnt['f'-'a'] -= x;
cnt['i'-'a'] -= x;
cnt['v'-'a'] -= x;
cnt['e'-'a'] -= x;
// seven
x = cnt['v'-'a'];
num[7] = x;
cnt['s'-'a'] -= x;
cnt['e'-'a'] -= x;
cnt['v'-'a'] -= x;
cnt['e'-'a'] -= x;
cnt['n'-'a'] -= x;
// nine
x = cnt['n'-'a'];
x/=2;
num[9] = x;
cnt['n'-'a'] -= x;
cnt['i'-'a'] -= x;
cnt['n'-'a'] -= x;
cnt['e'-'a'] -= x;
// eight
x = cnt['e'-'a'];
num[8] = x;
cnt['e'-'a'] -= x;
cnt['i'-'a'] -= x;
cnt['g'-'a'] -= x;
cnt['h'-'a'] -= x;
cnt['t'-'a'] -= x;
for (int i = 0; i < 10; i++) {
while (num[i] > 0) {
sb.append(""+i);
num[i]--;
}
}
return sb.toString();
}
}