Find length of longest substring with at most K normal characters | Function to find maximum length of normal substrings ; keeps count of normal characters ; indexes of substring ; maintain length of longest substring with at most K normal characters ; get position of character ; check if current character is normal ; check if normal characters count exceeds K ; update answer with substring length ; get position of character ; check if character is normal then decrement count ; Driver code ; initialise the string
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 , right = 0 , 0 NEW_LINE ans = 0 NEW_LINE while ( right < N ) : NEW_LINE INDENT while ( right < N and count <= K ) : NEW_LINE INDENT pos = ord ( P [ right ] ) - ord ( ' a ' ) NEW_LINE if ( Q [ pos ] == '0' ) : 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 pos = ord ( P [ left ] ) - ord ( ' a ' ) NEW_LINE left += 1 NEW_LINE if ( Q [ pos ] == '0' ) : 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 if ( __name__ == " _ _ main _ _ " ) : NEW_LINE INDENT P = " giraffe " NEW_LINE Q = "01111001111111111011111111" NEW_LINE K = 2 NEW_LINE N = len ( P ) NEW_LINE print ( maxNormalSubstring ( P , Q , K , N ) ) NEW_LINE DEDENT