text: Longest substring such that no three consecutive characters are same | C ++ 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: #include <bits/stdc++.h> NEW_LINE using namespace std ; 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 [ i ] != s [ i - 1 ] s [ i ] != s [ i - 2 ] ) temp ++ ; else { ans = max ( temp , ans ) ; temp = 2 ; } } ans = max ( temp , ans ) ; return ans ; } int main ( ) { string s = " baaabbabbb " ; cout << maxLenSubStr ( s ) ; return 0 ; }