[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:

  1. Input contains only lowercase English letters.
  2. 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.
  3. Input length is less than 50,000.
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class Solution {
void addAndRemove(unordered_map<char, int>& cnt, unordered_map<char, int>& m, char target, char unique, string s) {
m[target] = cnt[unique];
for(int i = 0; i < s.length(); i++) {
cnt[s[i]] -= m[target];
}

return;
}
public:
string originalDigits(string s) {
unordered_map<char,int> cnt;
unordered_map<char, int> m;
stringstream ss;
for(int i = 0; i < s.length(); i++) {
cnt[s[i]]++;
}

if(cnt.count('z') && cnt['z'] != 0) {
addAndRemove(cnt, m, '0', 'z', "zero");
}
if(cnt.count('x') && cnt['x'] != 0) {
addAndRemove(cnt, m, '6', 'x', "six");
}
if(cnt.count('g') && cnt['g'] != 0) {
addAndRemove(cnt, m, '8', 'g', "eight");
}
if(cnt.count('u') && cnt['u'] != 0) {
addAndRemove(cnt, m, '4', 'u', "four");
}
if(cnt.count('w') && cnt['w'] != 0) {
addAndRemove(cnt, m, '2', 'w', "two");
}
if(cnt.count('f') && cnt['f'] != 0) {
addAndRemove(cnt, m, '5', 'f', "five");
}
if(cnt.count('t') && cnt['t'] != 0) {
addAndRemove(cnt, m, '3', 't', "three");
}
if(cnt.count('o') && cnt['o'] != 0) {
addAndRemove(cnt, m, '1', 'o', "one");
}
if(cnt.count('s') && cnt['s'] != 0) {
addAndRemove(cnt, m, '7', 's', "seven");
}
if(cnt.count('i') && cnt['i'] != 0) {
addAndRemove(cnt, m, '9', 'i', "nine");
}


for(char i = '0'; i <= '9'; i++) {
if(m.count(i)) {
while(m[i]) {
ss<<i;
m[i]--;
}
}
}

return ss.str();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/28/PS/LeetCode/reconstruct-original-digits-from-english/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.