Longest substring with no pair of adjacent characters are adjacent English alphabets | Java program for the above approach ; Function to find the longest substring satisfying the given condition ; Stores all temporary substrings ; Stores the longest substring ; Stores the length of the substring T ; Stores the first character of string S ; Traverse the string ; If the absolute difference is 1 ; Update the length of substring T ; Update the longest substring ; Otherwise , stores the current character ; Again checking for longest substring and update accordingly ; Print the longest substring ; Driver Code ; Given string ; Function call to find the longest substring satisfying given condition
import java . io . * ; class GFG { static void findSubstring ( String S ) { String T = " " ; String ans = " " ; int l = 0 ; T += S . charAt ( 0 ) ; for ( int i = 1 ; i < S . length ( ) ; i ++ ) { if ( Math . abs ( S . charAt ( i ) - S . charAt ( i - 1 ) ) == 1 ) { l = T . length ( ) ; if ( l > ans . length ( ) ) { ans = T ; } T = " " ; T += S . charAt ( i ) ; } else { T += S . charAt ( i ) ; } } l = T . length ( ) ; if ( l > ans . length ( ) ) { ans = T ; } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { String S = " aabdml " ; findSubstring ( S ) ; } }