Longest substring with no pair of adjacent characters are adjacent English alphabets | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findSubstring ( string S ) { string T = " " ; string ans = " " ; int l = 0 ; T += S [ 0 ] ; for ( int i = 1 ; i < S . length ( ) ; i ++ ) { if ( abs ( S [ i ] - S [ i - 1 ] ) == 1 ) { l = T . length ( ) ; if ( l > ans . length ( ) ) { ans = T ; } T = " " ; T += S [ i ] ; } else { T += S [ i ] ; } } l = ( int ) T . length ( ) ; if ( l > ( int ) ans . length ( ) ) { ans = T ; } cout << ans << endl ; } int main ( ) { string S = " aabdml " ; findSubstring ( S ) ; return 0 ; }