Maximize depend of Substrings containing at the very least 1 vowel and 1 consonant


View Dialogue

Enhance Article

Save Article

Like Article

View Dialogue

Enhance Article

Save Article

Like Article

Given a string S consisting of solely lowercase English letters of size N, the duty is to search out the depend of substrings such that every substring comprises at the very least 1 vowel and 1 consonant.

Examples:

Enter: S = “happybirthday”
Output: 3
Clarification: S will be divided as “ha”, “ppybi”, “rthday”

Enter: S = “geeksforgeeks”
Output 5
Clarification: S will be divided as ge“, “ek“, “sfo“, “rge”, “eks”

 

Strategy: To resolve the issue observe the beneath concept:

The concept is to use the grasping method, traverse the string, and each time we encounter 1 vowel and 1 consonant improve the depend by 1 and reset the variety of vowels and consonants to 0.

Observe the steps beneath to unravel the issue:

  • Initialize variable ans = 0, haveVowels = false (present string have vowels or not), haveConsonants = false (present string have consonants or not)
  • Journey over the string by every character
    • If present character is vowels make the haveVowels = true else haveConsonants = true
    • Every time each are true then think about present subsegment is a legitimate substring, improve ans by 1, make haveVowels = false and haveConsonants = false.

Beneath is the implementation of the above method.

Python3

  

def strengthOfString(S):

    ans = 0

    N = len(S)

  

    

    

    haveVowels = False

    haveConsonants = False

  

    

    for s in S:

  

        

        

        if s in "aeiou":

            haveVowels = True

        else:

            haveConsonants = True

  

        

        

        if haveVowels and haveConsonants:

            ans += 1

            haveVowels = False

            haveConsonants = False

  

    

    return ans

  

if __name__ == "__main__":

    S = "happybirthday"

  

    

    ans = strengthOfString(S)

    print(ans)

Time Complexity: O(N)
Auxiliary House: O(1)

Leave a Reply

Your email address will not be published.