10 line 6ms c++ impl


  • 0
    T
    class Solution {
    public:
        int lengthOfLongestSubstringKDistinct(string s, int k) {
            // use hash table to recode distinct char freq
            // update maximum length when the rule is broken
            int maxlen = 0, nchar = 0, sz = s.size();
            int hash[128] = {0};
            for (int i = 0, j = 0; i < sz; ++i) {
                if (!hash[s[i]]++) ++nchar;
                if (nchar <= k) maxlen = max(maxlen, i-j+1);
                while (nchar > k) {
                    if (!--hash[s[j++]]) --nchar;
                }
            }
            return maxlen;
        }
    };
    

Log in to reply
 

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