Length of the longest substring that do not contain any palindrome | Java implementation of the above approach ; Function to find the length of the longest substring ; initializing the variables ; checking palindrome of size 2 example : aa ; checking palindrome of size 3 example : aba ; else incrementing length of substring ; max1 = Math . max ( max1 , len + 1 ) ; finding maximum ; if there exits single character then it is always palindrome ; Driver Code
import java . util . Arrays ; import java . lang . Math ; class GFG { public static int lenoflongestnonpalindrome ( String s ) { int max1 = 1 , len = 0 ; char [ ] new_str = s . toCharArray ( ) ; for ( int i = 0 ; i < new_str . length - 1 ; i ++ ) { if ( new_str [ i ] == new_str [ i + 1 ] ) len = 0 ; else if ( i > 0 && ( new_str [ i + 1 ] == new_str [ i - 1 ] ) ) len = 1 ; len ++ ; } if ( max1 == 1 ) return 0 ; else return max1 ; } public static void main ( String [ ] args ) { String s = " synapse " ; System . out . println ( lenoflongestnonpalindrome ( s ) ) ; } }