Is this not a simpler solution that just manipulates the k variable and tests whether a character can be found in a string using Python’s “in” functionality?
def longest_substring_with_k_distinct(str1, k):
windowStart = 0
best_result = ""
result = ""
k_orig = k
for windowEnd in range(0, len(str1)):
if str1[windowEnd] not in result and k > 0:
result += str1[windowEnd]
k -= 1
elif str1[windowEnd] in result:
result += str1[windowEnd]
else:
if len(result) > len(best_result):
best_result = result
result = ""
k = k_orig
return len(best_result)