Here, we will see how to solve Count the Number of Vowel Strings in Range Solution of leet code 2586 problem.
You are given a 0-indexed array of string words
and two integers left
and right
.
A string is called a vowel string if it starts with a vowel character and ends with a vowel character where vowel characters are 'a'
, 'e'
, 'i'
, 'o'
, and 'u'
.
You have to return the number of vowel strings words[i]
where i
belongs to the inclusive range [left, right]
.
Example 1:
Input: words = ["are","xyz","u"], left = 0, right = 2 Output: 2 Explanation: - "are" is a vowel string because it starts with 'a' and ends with 'e'. - "xyz" is not a vowel string because it does not start and end with a vowel. - "u" is a vowel string because it starts with 'u' and ends with 'u'. The number of vowel strings in the mentioned range is 2.
Example 2:
Input: words = ["hey","aeo","mu","ooo","artro"], left = 1, right = 4 Output: 3 Explanation: - "aeo" is a vowel string because it starts with 'a' and ends with 'o'. - "mu" is not a vowel string because it does not start with a vowel. - "ooo" is a vowel string because it starts with 'o' and ends with 'o'. - "artro" is a vowel string because it starts with 'a' and ends with 'o'. The number of vowel strings in the mentioned range is 3.
Approach:
- Iterate through array of words start from given left to right index.
- Check first and last character of each word whether It’s vowel or not
- If the word start and ends with vowel, increment the count
- Return the count at the end.
Count the Number of Vowel Strings in Range Solution in C++ and go:
Here, we will be solving problem in multiple ways with code.
C++ code 1:
class Solution { public: bool IsVowel(char c) { return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') ; } int vowelStrings(vector<string>& strs, int l, int r) { int cnt = 0 ; for(int i = l ; i <= r ; ++i) { cnt += (IsVowel(strs[i].front()) && IsVowel(strs[i].back())) ; } return cnt ; } };
C++ code 2:
class Solution { public: bool is_vowel(char ch) { if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { return true; } else { return false; } } int vowelStrings(vector<string>& words, int left, int right) { int count = 0; for(int i = left; i <= right; i++) { if(is_vowel(words[i][0]) && is_vowel(words[i][words[i].length()-1])) { count++; } } return count; } };
Go code 1:
func is_vowel(ch rune) bool { if ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' { return true } else { return false } } func vowelStrings(words []string, left int, right int) int { count := 0 for i := left; i <= right; i++ { if is_vowel(rune(words[i][0])) && is_vowel(rune(words[i][len(words[i])-1])) { count++ } } return count }
Output:
Input: words = ["are","xyz","u"], left = 0, right = 2
Output: 2
Time complexity: O(n)
Space complexity: O(1)
To check more leetcode problem’s solution. Pls click given below link:
https://techieindoor.com/category/leetcode/
https://techieindoor.com/category/interview-questions/