forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 15
/
reconstruct-original-digits-from-english.cpp
39 lines (35 loc) · 1.2 KB
/
reconstruct-original-digits-from-english.cpp
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
// Time: O(n)
// Space: O(1)
class Solution {
public:
string originalDigits(string s) {
const vector<string> numbers{"zero", "one", "two", "three",
"four", "five", "six", "seven",
"eight", "nine"};
vector<vector<int>> cnts(numbers.size(), vector<int>(26));
for (int i = 0; i < numbers.size(); ++i) {
for (const auto& c : numbers[i]) {
++cnts[i][c - 'a'];
}
}
// The order for greedy method.
vector<int> order{0, 2, 4, 6, 8, 1, 3, 5, 7, 9};
// The unique char in the order.
vector<char> unique_chars{'z', 'o', 'w', 't', 'u', 'f', 'x', 's', 'g', 'n'};
vector<int> cnt(26);
for (const auto& c : s) {
++cnt[c - 'a'];
}
string result;
for (const auto& i : order) {
while (cnt[unique_chars[i] - 'a'] > 0) {
for (int j = 0; j < cnt.size(); ++j) {
cnt[j] -= cnts[i][j];
}
result.push_back(i + '0');
}
}
sort(result.begin(), result.end());
return result;
}
};