Similar Problems

Similar Problems not available

Count Vowel Substrings Of A String - Leetcode Solution

Companies:

LeetCode:  Count Vowel Substrings Of A String Leetcode Solution

Difficulty: Easy

Topics: string hash-table  

Problem Statement

Given a string s, return the number of substrings that consist of vowels only.

A substring is a contiguous sequence of characters within a string.

Constraints:

  • 1 <= s.length <= 10^5
  • s consists of lowercase English letters.

Example:

Input: s = "abc" Output: 0

Input: s = "aeiou" Output: 15

Solution

Approach:

To solve this problem, we can follow the below steps:

  • Initialize a variable ans to store the result, which will be the count of all substrings having only vowels.

  • Initialize two variables i and j to track the indices of the leftmost and rightmost vowels present in the string, respectively.

  • Traverse the string s and for each character:

  • If the character is a vowel, update j to its index. If j increases, then all the substrings starting from i till j will be valid vowel substrings. We can add (j-i+1) to our existing ans value as it will give the count of all substrings that end at or after j.

  • If the character is not a vowel, update i to j+1 and reset j to the previous index of vowel found in the string. This is because all the substrings that end before j are invalid since they do not have a vowel.

  • Return the final answer stored in ans.

Let's see the implementation of the above approach:

class Solution { public: int countVowelStrings(string s) { int ans = 0, i = -1, j = -1; for (char c : s) { if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { j = s.find_last_of(c); // update j to the rightmost index of vowel c in the string ans += (j-i); // add substrings that end at or after j and start at or after i } else { i = j+1; // set i to the index after j j = s.find_last_of("aeiou",j); // set j to the previous index of vowel found in the string } } return ans; } };

Time Complexity:

  • The time complexity of the above approach is O(N), where N is the length of the input string s.

Space Complexity:

  • The space complexity of the above approach is O(1), as we are not using any extra space.

Count Vowel Substrings Of A String Solution Code

1