Skip to content

Commit a0a5664

Browse files
authored
Create reconstruct-original-digits-from-english.py
1 parent d94011a commit a0a5664

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
# Given a non-empty string containing an out-of-order English representation
5+
# of digits 0-9, output the digits in ascending order.
6+
#
7+
# Note:
8+
# Input contains only lowercase English letters.
9+
# Input is guaranteed to be valid and can be transformed to its original digits.
10+
# That means invalid inputs such as "abc" or "zerone" are not permitted.
11+
# Input length is less than 50,000.
12+
# Example 1:
13+
# Input: "owoztneoer"
14+
#
15+
# Output: "012"
16+
# Example 2:
17+
# Input: "fviefuro"
18+
#
19+
# Output: "45"
20+
21+
from collections import Counter
22+
23+
class Solution(object):
24+
def originalDigits(self, s):
25+
"""
26+
:type s: str
27+
:rtype: str
28+
"""
29+
# The count of each char in each number string.
30+
cnts = [Counter(_) for _ in ["zero", "one", "two", "three", \
31+
"four", "five", "six", "seven", \
32+
"eight", "nine"]]
33+
34+
# The order for greedy method.
35+
order = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]
36+
37+
# The unique char in the order.
38+
unique_chars = ['z', 'o', 'w', 't', 'u', \
39+
'f', 'x', 's', 'g', 'n']
40+
41+
cnt = Counter(list(s))
42+
res = []
43+
for i in order:
44+
while cnt[unique_chars[i]] > 0:
45+
cnt -= cnts[i]
46+
res.append(i)
47+
res.sort()
48+
49+
return "".join(map(str, res))

0 commit comments

Comments
 (0)