423. Reconstruct Original Digits from English

ss
Mar 29, 2021

--

會有很多字母被打散在一個字串

我們可以從這個字串, 撿出字母, 然後看能不能湊成一個數字的字串

舉例來說

"noe"
我們可以剪出來湊成
"one" -> 1

我們可以先算一些字母比較特殊的, 像是只有zero有z, two 有w, six有x, four有u, eight有g

所以我們只要在字串中發現有兩個z, 就代表一定有兩個zero, 以此類推, 最後在清算剩下的就行了

class Solution {
public:
string originalDigits(string s) {
string res;
vector<string> words = {"zero", "two", "four", "six", "eight",
"one", "three", "five", "seven", "nine"};
vector<int> nums{0, 2, 4, 6, 8, 1, 3, 5, 7, 9};
vector<char> chars{'z', 'w', 'u', 'x', 'g', 'o', 'h', 'f', 's', 'i'};
vector<int> count(26, 0);
for(char c: s) count[c - 'a']++;
for(int i = 0; i < 10;i++){
int cnt = count[chars[i] - 'a'];
for(int j = 0; j < words[i].size();j++){
count[words[i][j] - 'a'] -= cnt;
}
while(cnt > 0){
res += to_string(nums[i]);
cnt--;
}
}
sort(res.begin(), res.end());
return res;
}
};

--

--

ss
ss

No responses yet