Longest substring of vowels with no two adjacent alphabets same

Given string str consisting of lowercase alphabets, the task is to find the length of the longest substring such that all of its characters are vowels and no two adjacent alphabets are the same.
Examples: 

Input: str = “aeoibsddaeiouudb” 
Output:
Explanation: 
The longest substring of vowels in which no two adjacent letters are same is “aeiou” 
Length of substring = 5
Input: str = “geeksforgeeks” 
Output:
Explanation: 
The longest substring of vowels in which no two adjacent letters are same are “e” or “o”. 
Length of substring = 1 
 

Naive Approach: 
Generate all possible substrings from the given string. For each substring, check if all of its characters are vowels and no two adjacent characters are the same then compare the length of all such substrings and print the maximum length.
Below is the implementation of the above approach: 
 

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check a
// character is vowel or not
bool isVowel(char c)
{
    return (c == 'a' || c == 'e'
            || c == 'i' || c == 'o'
            || c == 'u');
}
 
// Function to check a
// substring is valid or not
bool isValid(string& s)
{
 
    int n = s.size();
 
    // If size is 1 then
    // check only first character
    if (n == 1)
        return (isVowel(s[0]));
 
    // If 0'th character is
    // not vowel then invalid
    if (isVowel(s[0]) == false)
        return false;
 
    for (int i = 1; i < n; i++) {
 
        // If two adjacent characters
        // are same or i'th char is
        // not vowel then invalid
        if (s[i] == s[i - 1]
            || !isVowel(s[i]))
            return false;
    }
 
    return true;
}
 
// Function to find length
// of longest substring
// consisting only of
// vowels and no similar
// adjacent alphabets
int findMaxLen(string& s)
{
    // Stores max length
    // of valid substring
    int maxLen = 0;
    int n = s.length();
 
    for (int i = 0; i < n; i++) {
 
        // For current substring
        string temp = "";
 
        for (int j = i; j < n; j++) {
 
            temp = temp + s[j];
 
            // Check if substring
            // is valid
            if (isValid(temp))
 
                // Size of substring
                // is (j-i+1)
                maxLen = max(
                    maxLen, (j - i + 1));
        }
    }
 
    return maxLen;
}
 
// Driver code
int main()
{
    string Str = "aeoibsddaeiouudb";
 
    cout << findMaxLen(Str) << endl;
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of
// the above approach
import java.io.*;
class GFG{
 
// Function to check a
// character is vowel or not
static boolean isVowel(char c)
{
    return (c == 'a' || c == 'e' ||
            c == 'i' || c == 'o' ||
            c == 'u');
}
 
// Function to check a
// subString is valid or not
static boolean isValid(String s)
{
    int n = s.length();
 
    // If size is 1 then
    // check only first character
    if (n == 1)
        return (isVowel(s.charAt(0)));
 
    // If 0'th character is
    // not vowel then invalidlen
    if (isVowel(s.charAt(0)) == false)
        return false;
 
    for (int i = 1; i < n; i++)
    {
 
        // If two adjacent characters
        // are same or i'th char is
        // not vowel then invalid
        if (s.charAt(i) == s.charAt(i - 1) ||
                  !isVowel(s.charAt(i)))
            return false;
    }
    return true;
}
 
// Function to find length
// of longest subString
// consisting only of
// vowels and no similar
// adjacent alphabets
static int findMaxLen(String s)
{
     
    // Stores max length
    // of valid subString
    int maxLen = 0;
    int n = s.length();
 
    for (int i = 0; i < n; i++)
    {
 
        // For current subString
        String temp = "";
 
        for (int j = i; j < n; j++)
        {
 
            temp = temp + s.charAt(j);
 
            // Check if subString
            // is valid
            if (isValid(temp))
 
                // Size of subString
                // is (j-i+1)
                maxLen = Math.max(maxLen,
                                 (j - i + 1));
        }
    }
    return maxLen;
}
 
// Driver code
public static void main (String[] args)
{
    String Str = "aeoibsddaeiouudb";
 
    System.out.println(findMaxLen(Str));
}
}
 
// This code is contributed by shubhamcoder

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of
# the above approach
 
# Function to check a
# character is vowel or not
def isVowel(c):
    return (c == 'a' or c == 'e' or
            c == 'i' or c == 'o' or
            c == 'u')
 
# Function to check a
# substring is valid or not
def isValid(s):
    n = len(s)
 
    # If size is 1 then
    # check only first character
    if (n == 1):
        return (isVowel(s[0]))
 
    # If 0'th character is
    # not vowel then invalid
    if (isVowel(s[0]) == False):
        return False
 
    for i in range (1, n):
 
        # If two adjacent characters
        # are same or i'th char is
        # not vowel then invalid
        if (s[i] == s[i - 1] or not
            isVowel(s[i])):
            return False
 
    return True
 
# Function to find length
# of longest substring
# consisting only of
# vowels and no similar
# adjacent alphabets
def findMaxLen(s):
 
    # Stores max length
    # of valid substring
    maxLen = 0
    n = len(s)
 
    for i in range (n):
 
        # For current substring
        temp = ""
 
        for j in range (i, n):
            temp = temp + s[j]
 
            # Check if substring
            # is valid
            if (isValid(temp)):
 
                # Size of substring
                # is (j-i+1)
                maxLen = (max(maxLen, (j - i + 1)))
 
    return maxLen
 
# Driver code
if __name__ == "__main__":
 
    Str = "aeoibsddaeiouudb"
    print (findMaxLen(Str))
 
# This code is contributed by Chitranayal

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the above approach
using System;
class GFG{
 
// Function to check a
// character is vowel or not
static bool isVowel(char c)
{
    return (c == 'a' || c == 'e' ||
            c == 'i' || c == 'o' ||
            c == 'u');
}
 
// Function to check a
// substring is valid or not
static bool isValid(string s)
{
 
    int n = s.Length;
 
    // If size is 1 then
    // check only first character
    if (n == 1)
        return (isVowel(s[0]));
 
    // If 0'th character is
    // not vowel then invalid
    if (isVowel(s[0]) == false)
        return false;
 
    for(int i = 1; i < n; i++)
    {
        
       // If two adjacent characters
       // are same or i'th char is
       // not vowel then invalid
       if (s[i] == s[i - 1] ||
          !isVowel(s[i]))
           return false;
    }
    return true;
}
 
// Function to find length
// of longest substring
// consisting only of
// vowels and no similar
// adjacent alphabets
static int findMaxLen(string s)
{
    // Stores max length
    // of valid substring
    int maxLen = 0;
    int n = s.Length;
 
    for(int i = 0; i < n; i++)
    {
        
       // For current substring
       string temp = "";
        
       for(int j = i; j < n; j++)
       {
           temp = temp + s[j];
            
           // Check if substring
           // is valid
           if (isValid(temp))
                
               // Size of substring
               // is (j-i+1)
               maxLen = Math.Max(maxLen,
                                (j - i + 1));
       }
    }
    return maxLen;
}
 
// Driver code
public static void Main()
{
    string Str = "aeoibsddaeiouudb";
 
    Console.WriteLine(findMaxLen(Str));
}
}
 
// This code is contributed by Code_Mech

chevron_right


Output: 

5



 

Time Complexity: O(N3)
Efficient Approach: 
A linear-time solution is possible for this problem. A substring will be considered as valid if all of its characters are vowel and no two adjacent ones are the same. The idea is to traverse the string and keep track of the longest valid substring.
The following are the detailed steps:  



  1. Create a variable cur to store the length of current valid substring and another variable maxVal to keep track of maximum cur found so far, initially, both are set to 0.
  2. If the character at index 0 is a vowel, then it is a valid substring of length 1, so maxVal = 1
  3. Traverse str starting from index 1. If the current character is not a vowel, no valid substring present, cur = 0
  4. If the current character is a vowel and 
    • Is different from the previous character, then includes it in the current valid substring and increment cur by 1. Update maxVal.
    • Is the same as the previous character, then a new valid substring starts from this character with cur reset to 1.
  5. The final value of maxVal gives the answer.

Below is the implementation of the above approach:
 

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check a
// character is vowel or not
bool isvowel(char c)
{
    return c == 'a' || c == 'e'
           || c == 'i' || c == 'o'
           || c == 'u';
}
// Function to find length
// of longest substring
// consisting only of
// vowels and no similar
// adjacent alphabets
int findMaxLen(string& s)
{
    // Stores max length
    // of valid subString
    int maxLen = 0;
 
    // Stores length of
    // current valid subString
    int cur = 0;
 
    if (isvowel(s[0]))
        cur = maxLen = 1;
 
    for (int i = 1; i < s.length(); i++) {
        if (isvowel(s[i])) {
            // If curr and prev character
            // are not same, include it
            if (s[i] != s[i - 1])
                cur += 1;
 
            // If same as prev one, start
            // new subString from here
            else
                cur = 1;
        }
 
        else {
            cur = 0;
        }
 
        // Store max in maxLen
        maxLen = max(cur, maxLen);
    }
 
    return maxLen;
}
 
// Driver code
int main()
{
    string Str = "aeoibsddaeiouudb";
    cout << findMaxLen(Str) << endl;
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of
// the above approach
 
public class GFG {
 
    // Function to check a
    // character is vowel or not
    static boolean isVowel(char x)
    {
        return (x == 'a' || x == 'e'
                || x == 'i' || x == 'o'
                || x == 'u');
    }
 
    // Function to find length
    // of longest substring
    // consisting only of
    // vowels and no similar
    // adjacent alphabets
    static int findMaxLen(String s)
    {
        // Stores max length
        // of valid subString
        int maxLen = 0;
 
        // Stores length of
        // current valid subString
        int cur;
 
        if (isVowel(s.charAt(0)))
            maxLen = 1;
 
        cur = maxLen;
 
        for (int i = 1; i < s.length(); i++) {
            if (isVowel(s.charAt(i))) {
                // If curr and prev character
                // are not same, include it
                if (s.charAt(i)
                    != s.charAt(i - 1))
                    cur += 1;
 
                // If same as prev one, start
                // new subString from here
                else
                    cur = 1;
            }
 
            else {
                cur = 0;
            }
 
            // Store max in maxLen
            maxLen = Math.max(cur, maxLen);
        }
 
        return maxLen;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String Str = "aeoibsddaeiouudb";
 
        System.out.println(findMaxLen(Str));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python implementation of
# the above approach
  
# Function to check a
# character is vowel or not
def isVowel(x):
       
    return (x == 'a' or x == 'e' or
            x == 'i' or x == 'o' or
            x == 'u');
   
# Function to find length
# of longest substring
# consisting only of
# vowels and no similar
# adjacent alphabets
def findMaxLen(s):
  
    # Stores max length
    # of valid subString
    maxLen = 0
     
    # Stores length of
    # current valid subString
    cur = 0
      
    if(isVowel(s[0])):
        maxLen = 1;
          
    cur = maxLen
      
    for i in range(1, len(s)):
          
        if(isVowel(s[i])):
            # If curr and prev character
            # are not same, include it
            if(s[i] != s[i-1]):
                cur += 1
              
            # If same as prev one, start
            # new subString from here   
            else:
                cur = 1
          
        else:
            cur = 0;
          
        # Store max in maxLen
        maxLen = max(cur, maxLen);
      
    return maxLen
   
# Driver code
  
Str = "aeoibsddaeiouudb"
      
print(findMaxLen(Str))

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of
// the above approach
 
using System;
 
public class GFG {
 
    // Function to check a
    // character is vowel or not
    public static bool isVowel(char x)
    {
        return (x == 'a' || x == 'e'
                || x == 'i' || x == 'o'
                || x == 'u');
    }
 
    // Function to find length
    // of longest substring
    // consisting only of
    // vowels and no similar
    // adjacent alphabets
    public static int findMaxLen(string s)
    {
        // Stores max length
        // of valid subString
        int maxLen = 0;
 
        // Stores length of
        // current valid subString
        int cur;
 
        if (isVowel(s[0]))
            maxLen = 1;
 
        cur = maxLen;
 
        for (int i = 1; i < s.Length; i++) {
            if (isVowel(s[i])) {
                // If curr and prev character
                // are not same, include it
                if (s[i] != s[i - 1])
                    cur += 1;
 
                // If same as prev one, start
                // new subString from here
                else
                    cur = 1;
            }
 
            else {
                cur = 0;
            }
 
            // Store max in maxLen
            maxLen = Math.Max(cur, maxLen);
        }
 
        return maxLen;
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        string Str = "aeoibsddaeiouudb";
 
        Console.WriteLine(findMaxLen(Str));
    }
}

chevron_right


Output: 

5



 

Time complexity: O(N) 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.