Given a string
Return the maximum number of vowel letters in any substring of
Vowel letters in English are (a, e, i, o, u).
s
and an integer k
.Return the maximum number of vowel letters in any substring of
s
with length k
.Vowel letters in English are (a, e, i, o, u).
Example 1:
Input: s = "abciiidef", k = 3
Output: 3
Approach
Explanation
Create an array of sizes the same as the size of the string.
1. If the first character is a vowel set arr[0] with 1, otherwise arr[0] with 0.
2. Iterate through the whole string from position 1 to the end.
a) If the character at the current position is a vowel then arr[currentPos]=arr[currentPos-1]+1
b) else arr[currentPos]=arr[currentPos-1]
3. Now iterate the array from the k to the end and update the maximum as (arr[currentPos]-arr[currentPos-k]) and the previous maximum.
4. Return the result as maximum.
Java
public class MaxVowels {public static void main(String[] args) {String s = "abciiidef";int k = 3;System.out.println(maxVowels(s, k));}static boolean isvowel(char c) {if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')return true;return false;}static int maxVowels(String s, int k) {int n = s.length();int arr[] = new int[n];if (isvowel(s.charAt(0)))arr[0] = 1;elsearr[0] = 0;for (int i = 1; i < n; i++) {if (isvowel(s.charAt(i)))arr[i] = arr[i - 1] + 1;elsearr[i] = arr[i - 1];}int max1 = 0;max1 = arr[k - 1];for (int i = k; i < n; i++) {int x = arr[i] - arr[i - k];if (x > max1)max1 = x;}return max1;}}
C++
#include <bits/stdc++.h>using namespace std;bool isvowel(char c){if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')return true;return false;}int maxVowels(string s, int k){int n = s.size();int arr[n];if (isvowel(s[0]))arr[0] = 1;elsearr[0] = 0;for (int i = 1; i < n; i++){if (isvowel(s[i]))arr[i] = arr[i - 1] + 1;elsearr[i] = arr[i - 1];}int max1 = 0;max1 = arr[k - 1];for (int i = k; i < n; i++){int x = arr[i] - arr[i - k];if (x > max1)max1 = x;}return max1;}int main(){string s = "abciiidef";int k = 3;cout << maxVowels(s, k);return 0;}
No comments:
Post a Comment