Length of longest substring having all characters as K | Java program for the above approach ; Function to find the length of longest sub - string having all characters same as character K ; Initialize variables ; Iterate till size of string ; Check if current character is K ; Assingning the max value to max_len ; Driver code ; Function call
import java . util . * ; class GFG { static int length_substring ( String S , char K ) { int curr_cnt = 0 , prev_cnt = 0 , max_len ; for ( int i = 0 ; i < S . length ( ) ; i ++ ) { if ( S . charAt ( i ) == K ) { curr_cnt += 1 ; } else { prev_cnt = Math . max ( prev_cnt , curr_cnt ) ; curr_cnt = 0 ; } } prev_cnt = Math . max ( prev_cnt , curr_cnt ) ; max_len = prev_cnt ; return max_len ; } public static void main ( String [ ] args ) { String S = " abcd1111aabc " ; char K = '1' ; System . out . print ( length_substring ( S , K ) ) ; } }