C++ using frequency array - a slightly different approach?


  • 0
    M

    This differs from other solutions I've seen -- of course maybe it's not that different and I just didn't look through enough posts ... In any case, in my own mind, this is pretty clean ;-)

            string originalDigits(const string& s)
            {
                int freqs[26] = { 0 };
    
                for (auto ch : s) {
                    freqs[ch - 'a']++;
                }
    
                auto exists = [&](char ch) {
                    return 0 < freqs[ch - 'a'];
                };
    
                auto remove = [&](const string& str) {
                    for(auto ch : str)
                        freqs[ch - 'a']--;
                };
    
                string result;
    
                // order matters
                while (exists('z')) { result += '0'; remove("zero"); }
                while (exists('w')) { result += '2'; remove("two"); }
                while (exists('x')) { result += '6'; remove("six"); }
                while (exists('u')) { result += '4'; remove("four"); }
                while (exists('s')) { result += '7'; remove("seven"); }
                while (exists('v')) { result += '5'; remove("five"); }
                while (exists('g')) { result += '8'; remove("eight"); }
                while (exists('r')) { result += '3'; remove("three"); }
                while (exists('i')) { result += '9'; remove("nine"); }
                while (exists('n')) { result += '1'; remove("one"); }
    
                sort(begin(result), end(result));
                return result;
            }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.