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.所有字母均为小写;
2.保证输入的字符串由0~9对应的英文单词组成(乱序),即原字符串一定可以还原成数字表示且没有多余字符;
3.输入字符串长度小于50000。
分析:
先统计输入字符串中各字符的个数,分别计为c
a、c
b、……c
z,设0~9分别有n
0、n
1、……n
9个,根据0~9对应英文单词(zero、one、two、three、four、five、six、seven、eight、nine)可知:
c
a=0
c
b=0
c
c=0
c
d=0
c
e=n
0+n
1+n
3*2+n
5+n
7*2+n
8+n
9
c
f=n
4+n
5
c
g=n
8
c
h=n
3+n
8
c
i=n
5+n
6+n
8+n
9
c
j=0
c
k=0
c
l=0
c
m=0
c
n=n
1+n
7+n
9*2
c
o=n
0+n
1+n
2+n
4
c
p=0
c
q=0
c
r=n
0+n
3+n
4
c
s=n
6+n
7
c
t=n
2+n
3+n
8
c
u=n
4
c
v=n
5+n
7
c
w=n
2
c
x=n
6
c
y=0
c
z=n0
由以上各等式可知:
n
0=c
z
n
2=c
w
n
4=c
u
n
6=c
x
n
8=c
g
n
5=c
f-n
4
n
1=c
o-n
0-n
2-n
4
n
3=c
h-n
8
n
7=c
s-n
6
n
9=c
i-n
5-n
6-n
8
当然,求解等式并不只有这一种,比如由前面的分析可知,n
7还可以由c
v-n
5得出,选取任一种均可。
由以上分析编写相应代码如下:
string originalDigits(string s) { string nums[10] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; int counts[10] = { 0 }; map<char, int> chars; for (char ch = 'a'; ch <= 'z'; ch++) chars[ch] = 0; for (char ch : s) chars[ch]++; counts[0] = chars['z']; counts[2] = chars['w']; counts[4] = chars['u']; counts[6] = chars['x']; counts[8] = chars['g']; counts[5] = chars['f'] - counts[4]; counts[1] = chars['o'] - counts[0] - counts[2] - counts[4]; counts[3] = chars['h'] - counts[8]; counts[7] = chars['s'] - counts[6]; counts[9] = chars['i'] - counts[5] - counts[6] - counts[8]; string rst; for (int i = 0; i < 10; i++) if (counts[i] > 0) rst.append(counts[i], i + '0'); return rst; }