A different approach to the problem, besides the popular math solution.
class Solution { vector<int> cnt; vector<int> ccnt; void _handle(char c, int d, string str) { if (ccnt[c - 'a'] > 0) { cnt[d] += ccnt[c - 'a']; for(auto cc : str) ccnt[cc - 'a'] -= cnt[d]; } } public: string originalDigits(string s) { cnt.assign(10, 0); ccnt.assign(26, 0); // count char freq for (auto c : s) ccnt[(c-'a')] += 1; // pass 1 - 0 2 4 6 8 _handle('z', 0, "zero"); _handle('w', 2, "two"); _handle('u', 4, "four"); _handle('x', 6, "six"); _handle('g', 8, "eight"); // pass 2 - 1 3 _handle('o', 1, "one"); _handle('r', 3, "three"); // pass 3 - 5 7 _handle('f', 5, "five"); _handle('s', 7, "seven"); // pass 4 - 9 _handle('i', 9, "nine"); string ret; for(int i = 0; i < cnt.size(); i ++) for(int j = 0; j < cnt[i]; j ++) ret += to_string(i); return ret; } };