Saturday, 16 Oct 2021

# Longest substring with no pair of adjacent characters are adjacent English alphabets

Longest substring with no pair of adjacent characters are adjacent English alphabets
Given a string S consisting of lowercase English alphabets, the task is to find the longest substring from the given string such that no two adjacent characters are neighbouring English alphabets.
Examples:

Input: S = “aabdml”Output: “bdm”Explanation: Substring “bdm” is the longest substring which satisfies the given condition.
Input: S = “abc”Output: “a”Explanation: Substrings “a”, “b”, “c” satisfies the given condition. Print any one of them.

Approach: Follow the steps below to solve the problem:Initialize an empty string, say T, to store all the temporary substrings during iteration.
Initialize another string, say ans, to store the longest substring as per the given conditions and a variable, say len, to store the length of the longest substring.
Append the first character of the string to ans.
Traverse the string in the range of indices [1, S.length()] and perform the following operations:
If the absolute difference between ASCII values of the adjacent characters is 1, then update ans and the length of the longest string and set T equal to the current character for the next iteration.
Otherwise, append the current character to string T.

Check again for the longest substring and update the values accordingly.
Print the longest substring obtained in variable ans.
Below is the implementation of the above approach:

C++

#include
using namespace std;

void findSubstring(string S)
{

string T = “”;

string ans = “”;

int l = 0;

T += S;

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