423. Reconstruct Original Digits from English

  • 43.1%

https://leetcode.com/problems/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.

1
2
3
4
5
> Example 1:
> Input: "owoztneoer"
>
> Output: "012"
>
1
2
3
4
5
> Example 2:
> Input: "fviefuro"
>
> Output: "45"
>

cpp

October 16, 2016

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
string originalDigits(string s) {
string res = "";
vector<int> alpha(26, 0);
for(int i=0; i<s.length(); i++)
alpha[s[i] - 'a']++;
int count = 0;
vector<int> num(10, 0);
num[0] = alpha['z'-'a'];
num[2] = alpha['w'-'a'];
num[3] = alpha['h'-'a'] - alpha['g'-'a'];
num[4] = alpha['u'-'a'];
num[5] = alpha['f'-'a'] - alpha['u'-'a'];
num[6] = alpha['x'-'a'];
num[7] = alpha['s'-'a'] - alpha['x'-'a'];
num[8] = alpha['g'-'a'];
num[9] = alpha['i'-'a'] - num[5] - num[6] - num[8];
num[1] = alpha['n'-'a'] - num[7] - 2*num[9];

for(int i=0; i<=9; i++)
for(int j=0; j<num[i]; j++)
res += to_string(i);

return res;
}
};

python

my solution:

98ms, , October 16, 2016

https://discuss.leetcode.com/topic/63425/my-python-mathematic-solution-o-n-easy-to-understand

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution(object):
def originalDigits(self, s):
"""
:type s: str
:rtype: str
"""
nums = [0]*26
for i in s:
nums[ord(i)-97] += 1
temp = [0]*10
temp[0] = nums[25]
temp[2] = nums[22]
temp[4] = nums[20]
temp[6] = nums[23]
temp[8] = nums[6]

temp[7] = nums[18] - temp[6]
temp[5] = nums[21] - temp[7]
temp[3] = nums[17] - temp[0] - temp[4]
temp[9] = nums[8] - temp[5] - temp[6] - temp[8]
temp[1] = nums[14] - temp[0] -temp[2] - temp[4]

res = ''
for i, n in enumerate(temp):
if n > 0:
res += str(i) * n

return res
谢谢你,可爱的朋友。