```
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;
}
};
```