Skip to content

Commit b5697fb

Browse files
authored
Create reconstruct-original-digits-from-english.cpp
1 parent 21987a2 commit b5697fb

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
2+
// Time: O(n)
3+
// Space: O(1)
4+
5+
class Solution {
6+
public:
7+
string originalDigits(string s) {
8+
const vector<string> numbers{"zero", "one", "two", "three",
9+
"four", "five", "six", "seven",
10+
"eight", "nine"};
11+
vector<vector<int>> cnts(numbers.size(), vector<int>(26));
12+
for (int i = 0; i < numbers.size(); ++i) {
13+
for (const auto& c : numbers[i]) {
14+
++cnts[i][c - 'a'];
15+
}
16+
}
17+
18+
// The order for greedy method.
19+
vector<int> order{0, 2, 4, 6, 8, 1, 3, 5, 7, 9};
20+
21+
// The unique char in the order.
22+
vector<char> unique_chars{'z', 'o', 'w', 't', 'u', 'f', 'x', 's', 'g', 'n'};
23+
vector<int> cnt(26);
24+
for (const auto& c : s) {
25+
++cnt[c - 'a'];
26+
}
27+
28+
string result;
29+
for (const auto& i : order) {
30+
while (cnt[unique_chars[i] - 'a'] > 0) {
31+
for (int j = 0; j < cnt.size(); ++j) {
32+
cnt[j] -= cnts[i][j];
33+
}
34+
result += to_string(i);
35+
}
36+
}
37+
sort(result.begin(), result.end());
38+
return result;
39+
}
40+
};

0 commit comments

Comments
 (0)