leetcode题目汇集 - Reconstruct Original Digits from English
423. Reconstruct Original Digits from English
题目要求:
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"
即:给定一个由数字0-9的英文组成,但是字符串是乱序的,如1的英文one可能表示为noe等等,题目要求找出每个数字表示的英文各有多少个,并按照数字0-9的顺序列出,如"owoeonztneoer"由英文zero,one,one,two组成,则输出为"0112"。
观察0-9的英文"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",可以发现一些字母只在某一个单词中出现,如z,w,u,x,g这5个单词,分别只出现在zero,two,four,six,eight中,那么这五个数字的个数就可以被确定了,由于含有o的单词有zero,two,four,one,其中前三个都被确定了,那么one的个数也就知道了;由于含有t的单词有two,three,eight,其中two,eight个数已知,那么three的个数就知道了;由于含有f的单词有four,five,其中four个数已知,那么five的个数就知道了;由于含有s的单词有six,seven,其中six个数已知,那么seven的个数就知道了;由于含有i的单词有six,eight,five,nine,其中前三个都被确定了,那么nine的个数就知道了,知道了这些问题就变的容易多了,我们按这个顺序"zero", "two", "four", "six", "eight", "one", "three", "five", "seven", "nine"就能找出所有的个数了。
代码如下:
public class Solution {
public String originalDigits(String s) {
int[] alphabetCount = new int[26];
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
alphabetCount[c - 'a']++;
}
int[] counts = new int[10];
counts[0] = alphabetCount['z' - 'a'];
counts[2] = alphabetCount['w' - 'a'];
counts[4] = alphabetCount['u' - 'a'];
counts[6] = alphabetCount['x' - 'a'];
counts[8] = alphabetCount['g' - 'a'];
counts[1] = alphabetCount['o' - 'a'] - counts[0] - counts[2] - counts[4];
counts[3] = alphabetCount['t' - 'a'] - counts[2] - counts[8];
counts[5] = alphabetCount['f' - 'a'] - counts[4];
counts[7] = alphabetCount['s' - 'a'] - counts[6];
counts[9] = alphabetCount['i' - 'a'] - counts[5] - counts[6] - counts[8];
String result = "";
for (int i = 0; i <= 9; i++) {
while (counts[i] > 0) {
result += i;
counts[i]--;
}
}
return result;
}
}
参考资料: