C++ with no explicit loops


  • 0
    M

    It may be considered better style today to write

    for(char ch : s)
        freq[ch]++
    

    instead of using for_each;

        class Solution {
        public:
            int firstUniqChar(const string& s)
            {
                int freq[256] = { 0 };
    
                for_each(
                    begin(s), end(s),
                    [&](char ch) { freq[ch]++; });
    
                auto iter = find_if(
                    begin(s), end(s),
                    [&](char ch) { return freq[ch] == 1; });
    
                int where = -1;
                if (iter != end(s))
                {
                    where = distance(begin(s), iter);
                }
    
                return where;
            }
        };
    '''

Log in to reply
 

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