Longest substring with atmost K characters from the given set of characters | Function to find the longest substring in the string which contains atmost K characters from the given set of characters ; Base Condition ; Count for Characters from set in substring ; Two pointers ; Loop to iterate until right pointer is not equal to N ; Loop to increase the substring length until the characters from set are at most K ; Check if current pointer points a character from set ; If the count of the char is exceeding the limit ; update answer with substring length ; Increment the left pointer until the count is less than or equal to K ; If the character which comes out then decrement the count by 1 ; Driver Code ; Construction of set ; Output result
def maxNormalSubstring ( P , Q , K , N ) : NEW_LINE INDENT if ( K == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT count = 0 NEW_LINE left = 0 NEW_LINE right = 0 NEW_LINE ans = 0 NEW_LINE while ( right < N ) : NEW_LINE INDENT while ( right < N and count <= K ) : NEW_LINE INDENT if ( P [ right ] in Q ) : NEW_LINE INDENT if ( count + 1 > K ) : NEW_LINE INDENT break NEW_LINE DEDENT else : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT right += 1 NEW_LINE if ( count <= K ) : NEW_LINE INDENT ans = max ( ans , right - left ) NEW_LINE DEDENT DEDENT while ( left < right ) : NEW_LINE INDENT left += 1 NEW_LINE if ( P [ left - 1 ] in Q ) : NEW_LINE INDENT count -= 1 NEW_LINE DEDENT if ( count < K ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT P = " giraffe " NEW_LINE Q = { chr } NEW_LINE Q . add ( ' a ' ) NEW_LINE Q . add ( ' f ' ) NEW_LINE Q . add ( ' g ' ) NEW_LINE Q . add ( ' r ' ) NEW_LINE K = 2 NEW_LINE N = len ( P ) NEW_LINE print ( maxNormalSubstring ( P , Q , K , N ) ) NEW_LINE