text: Longest substring such that no three consecutive characters are same | Java implementation of the approach ; Function to return the length of the longest substring such that no three consecutive characters are same ; If the length of the given string is less than 3 ; Initialize temporary and final ans to 2 as this is the minimum length of substring when length of the given string is greater than 2 ; Traverse the string from the third character to the last ; If no three consecutive characters are same then increment temporary count ; Else update the final ans and reset the temporary count ; Driver code
code: import java . util . * ; class GFG { static int maxLenSubStr ( String s ) { if ( s . length ( ) < 3 ) return s . length ( ) ; int temp = 2 ; int ans = 2 ; for ( int i = 2 ; i < s . length ( ) ; i ++ ) { if ( s . charAt ( i ) != s . charAt ( i - 1 ) || s . charAt ( i ) != s . charAt ( i - 2 ) ) temp ++ ; else { ans = Math . max ( temp , ans ) ; temp = 2 ; } } ans = Math . max ( temp , ans ) ; return ans ; } public static void main ( String [ ] args ) { String s = " baaabbabbb " ; System . out . println ( maxLenSubStr ( s ) ) ; } }