Find length of longest substring with at most K normal characters | Java implementation to 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
class GFG { static int maxNormalSubString ( char [ ] P , char [ ] Q , int K , int N ) { if ( K == 0 ) return 0 ; int count = 0 ; int left = 0 , right = 0 ; int ans = 0 ; while ( right < N ) { while ( right < N && count <= K ) { int pos = P [ right ] - ' a ' ; if ( Q [ pos ] == '0' ) { if ( count + 1 > K ) break ; else count ++ ; } right ++ ; if ( count <= K ) ans = Math . max ( ans , right - left ) ; } while ( left < right ) { int pos = P [ left ] - ' a ' ; left ++ ; if ( Q [ pos ] == '0' ) count -- ; if ( count < K ) break ; } } return ans ; } public static void main ( String [ ] args ) { String P = " giraffe " , Q = "01111001111111111011111111" ; int K = 2 ; int N = P . length ( ) ; System . out . print ( maxNormalSubString ( P . toCharArray ( ) , Q . toCharArray ( ) , K , N ) ) ; } }