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


In the realm of string manipulation, identifying patterns and extracting meaningful substrings are common tasks. One intriguing problem involves finding the longest substring where no adjacent characters are adjacent English alphabets. In this article, we'll delve into an efficient solution to this problem, along with a clear explanation and an example test case.

Problem Statement

Given a string of lowercase English alphabets, we need to find the length of the longest substring where no adjacent characters are adjacent English alphabets. For example, in the string "abacabx", the longest substring satisfying this condition is "abx", with a length of 3.

Approach and Algorithm

To solve this problem, we can utilize a greedy approach. We'll iterate through the given string and check if the current character and the previous character are adjacent English alphabets. If they are, we'll start a new substring. Otherwise, we'll extend the existing substring. By updating the length of the longest substring whenever it exceeds the previous maximum, we can find the desired result.

Implementation

Here're the codes that solves the problem −

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

// Function to find the longest substring with consecutive characters having a difference of 1 in their ASCII values
int findLongestSubstring(const char* str) {
   int maxLength = 0;
   int currentLength = 1;
    
   // Loop through the characters in the string
   for (int i = 1; i < strlen(str); i++) {
      // Check if the difference between adjacent characters is not equal to 1
      if (abs(str[i] - str[i - 1]) != 1) {
         currentLength++;  // Increment the current substring length
      } else {
         maxLength = (maxLength > currentLength) ? maxLength : currentLength;   // Update the maximum length if needed
         currentLength = 1;  // Reset the current substring length
      }
   }
   
   maxLength = (maxLength > currentLength) ? maxLength : currentLength;    // Check for the last substring
   return maxLength;  // Return the length of the longest substring
}

int main() {
   const char* inputString = "abacabx";
   int longestSubstringLength = findLongestSubstring(inputString);
   
   printf("Longest substring length: %d\n", longestSubstringLength);
   
   return 0;
}

Output

Longest substring length: 3
#include <iostream>
#include <string>
using namespace std;

int findLongestSubstring(const string& str) {
   int maxLength = 0;
   int currentLength = 1;
   
   for (int i = 1; i < str.length(); i++) {
      if (abs(str[i] - str[i - 1]) != 1) {
         currentLength++;
      } else {
         maxLength = max(maxLength, currentLength);
         currentLength = 1;
      }
   }
   
   maxLength = max(maxLength, currentLength);
   return maxLength;
}

int main() {
   string inputString = "abacabx";
   int longestSubstringLength = findLongestSubstring(inputString);
   
   cout << "Longest substring length: " << longestSubstringLength << endl;
   
   return 0;
}

Output

Longest substring length: 3
public class LongestSubstring {

   public static int findLongestSubstring(String str) {
      int maxLength = 0;
      int currentLength = 1;

      // Loop through the characters in the string
      for (int i = 1; i < str.length(); i++) {
         // Check if the difference between adjacent characters is not equal to 1
         if (Math.abs(str.charAt(i) - str.charAt(i - 1)) != 1) {
            currentLength++; // Increment the current substring length
         } else {
            maxLength = Math.max(maxLength, currentLength); // Update the maximum length if needed
            currentLength = 1; // Reset the current substring length
         }
      }

      maxLength = Math.max(maxLength, currentLength); // Check for the last substring
      return maxLength; // Return the length of the longest substring
   }

   public static void main(String[] args) {
      String inputString = "abacabx";
      int longestSubstringLength = findLongestSubstring(inputString);

      System.out.println("Longest substring length: " + longestSubstringLength);
   }
}

Output

Longest substring length: 3
def find_longest_substring(s):
   max_length = 0
   current_length = 1

   # Loop through the characters in the string
   for i in range(1, len(s)):
      # Check if the difference between adjacent characters is not equal to 1
      if abs(ord(s[i]) - ord(s[i - 1])) != 1:
         current_length += 1 # Increment the current substring length
      else:
         max_length = max(max_length, current_length) # Update the maximum length if needed
         current_length = 1 # Reset the current substring length

   max_length = max(max_length, current_length) # Check for the last substring
   return max_length # Return the length of the longest substring

def main():
   input_string = "abacabx"
   longest_substring_length = find_longest_substring(input_string)

   print("Longest substring length:", longest_substring_length)

if __name__ == "__main__":
   main()

Output

Longest substring length: 3

Explanation of the Code

The function findLongestSubstring takes the input string as a parameter and returns the length of the longest substring with no adjacent English alphabet characters.

We initialize maxLength and currentLength to 0 and 1, respectively. We then iterate through the string starting from the second character. If the absolute difference between the current character and the previous character is not equal to 1, we increment currentLength to extend the current substring. Otherwise, we update maxLength if the current length exceeds the previous maximum and reset currentLength to 1.

Finally, we return the maximum length found. In the main function, we provide an example input string "abacabx" and print the length of the longest substring.

Example Test Case

Let's consider the example string "abacabx" to demonstrate our solution.

string inputString = "abacabx";

In this case, the longest substring with no adjacent English alphabet characters is "abx" with a length of 3.

Conclusion

By employing a simple and efficient approach, we have successfully solved the problem of finding the longest substring with no adjacent English alphabet characters using C++. Understanding the provided code and the explanation will enable you to tackle similar problems involving string manipulation.

Updated on: 23-Oct-2023

230 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements