Largest Substring with at most k different char

code

class Solution {
public:
    /**
     * @param s : A string
     * @return : The length of the longest substring 
     *           that contains at most k distinct characters.
     */
    int lengthOfLongestSubstringKDistinct(string s, int k) {
        // write your code here
        if(s.length() == 0)
        {
            return 0;
        }

        int i = 0;
        int j = 0;
        map<char, int> hash;

        int ret = 0;
        int count = 0;

        for(; i < s.length(); i++)
        {
            while(j < s.length())
            {
                count++;
                char cur = s[j];
                hash[cur]++;
                j++;

                if((int)hash.size() <= k)
                {
                    ret = max(ret, count);
                }
                else
                {
                    break;
                }
            }

            // pop s[i] from hash and count--
            count--;
            hash[s[i]]--;
            if(hash[s[i]] == 0)
            {
                hash.erase(s[i]);
            }
        }

        return ret;
    }
};

results matching ""

    No results matching ""