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"
这道题是从乱序英文字符中重构阿拉伯数字,题目难度为Medium。
我们不妨先把所有数字的英文单词罗列出来:
zero one
two three
four five
six seven
eight nine
不难看出某些字符是一些数字所独有的,例如‘zero’中的‘z’在其他九个数字中是没有的。题目限定打乱的字符串能够完全匹配为数字,不存在错误的情况,因此每有一个特殊字符即表明有一个相应数字,统计‘z’出现的次数即可得出‘zero’的个数,‘two’、‘four’、‘six’和‘eight’类似,比较巧这几个数字都是偶数。奇数中没有独有的字符,以‘one’为例,‘o’只在‘zero’、‘one’、‘two’和‘four’中出现,而其他三个数字的个数已经得到,统计‘o’的个数减去‘zero’、‘two’和‘four’的个数即可得到‘one’的个数。其他奇数个数可以通过类似的方法得出。具体代码:
class Solution {
public:
string originalDigits(string s) {
vector<int> cnt(10, 0);
string ret = "";
for(auto c:s) {
switch(c) {
case 'z': ++cnt[0]; break;
case 'w': ++cnt[2]; break;
case 'u': ++cnt[4]; break;
case 'x': ++cnt[6]; break;
case 'g': ++cnt[8]; break;
case 'o': ++cnt[1]; break;
case 'h': ++cnt[3]; break;
case 'f': ++cnt[5]; break;
case 's': ++cnt[7]; break;
case 'i': ++cnt[9]; break;
default: break;
}
}
cnt[1] = cnt[1] - cnt[0] - cnt[2]- cnt[4];
cnt[3] -= cnt[8];
cnt[5] -= cnt[4];
cnt[7] -= cnt[6];
cnt[9] = cnt[9] - cnt[5] - cnt[6] - cnt[8];
for(int i=0; i<10; ++i)
ret += string(cnt[i], '0' + i);
return ret;
}
};