Length of the longest substring with no consecutive same letters | Java implementation of the approach ; Function to return the length of the required sub - string ; Get the length of the string ; Iterate in the string ; Check for not consecutive ; If cnt greater than maxi ; Re - initialize ; Check after iteration is complete ; Driver code
import java . lang . Math ; class GfG { static int longestSubstring ( String s ) { int cnt = 1 , maxi = 1 ; int n = s . length ( ) ; for ( int i = 1 ; i < n ; i ++ ) { if ( s . charAt ( i ) != s . charAt ( i - 1 ) ) cnt ++ ; else { maxi = Math . max ( cnt , maxi ) ; cnt = 1 ; } } maxi = Math . max ( cnt , maxi ) ; return maxi ; } public static void main ( String [ ] args ) { String s = " ccccdeededff " ; System . out . println ( longestSubstring ( s ) ) ; } }