the key difference is that it keeps track of the latest position of the char not the frequency.
def longest_substring_with_k_distinct(str1, k):
max_len = window_start = 0
existed_c = {}
for window_end, value in enumerate(str1):
existed_c[value] = window_end
while len(existed_c) > k:
if existed_c[str1[window_start]] == window_start:
del existed_c[str1[window_start]]
window_start += 1
max_len = max(max_len, window_end-window_start+1)
return max_len