1456. Maximum Number of Vowels in a Substring of Given Length (使用 C 語言解題)

Medium
Topics
Companies
Hint

Given a string 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', and 'u'.

 

Example 1:

Input: s = "abciiidef", k = 3
Output: 3
Explanation: The substring "iii" contains 3 vowel letters.

Example 2:

Input: s = "aeiou", k = 2
Output: 2
Explanation: Any substring of length 2 contains 2 vowels.

Example 3:

Input: s = "leetcode", k = 3
Output: 2
Explanation: "lee", "eet" and "ode" contain 2 vowels.

 

Constraints:

  • 1 <= s.length <= 105
  • s consists of lowercase English letters.
  • 1 <= k <= s.length

google 翻譯:

給定一個字串 s 和一個整數 k,傳回 s 中長度為 k 的任何子字串中元音字母的最大數量。

英文的母音字母有「a」、「e」、「i」、「o」和「u」。



想法一:

同上一例的概念,先算出陣列開頭 k 長度的元音數,
之後再去頭加尾的跑完陣列

寫法一:

bool checkVowel(char c) { // 元音判斷
if(c == 'a' || c == 'e' || c == 'i' || c =='o' || c == 'u')
return true;
return false;
}
int maxVowels(char* s, int k) {
int left = 0;
int right = 0;
int vowel = 0, max = 0;

// 計算開頭的元音個數
while(right < k) {
if(checkVowel(s[right++]))
vowel++;
}
max = vowel; // 指定為目前最大值

// 跑完剩下的字元
while(s[right]) {
if(checkVowel(s[right++])) // 下一個要加入 k 長度尾的元音
vowel++;
if(checkVowel(s[left++])) // 去掉 k 長度開頭的元音
vowel--;
if(max < vowel) // 存最大值
max = vowel;
}
return max;
}

結果一:
精益求精,尋求更好的寫法...


想法二:

目前能做的是減少判斷個數

寫法二:

int checkVowel(char c) { // 元音判斷
if(c == 'a' || c == 'e' || c == 'i' || c =='o' || c == 'u')
return 1;
return 0;
}
int maxVowels(char* s, int k) {
int left = 0;
int right = 0;
int vowel = 0, max = 0;

// 計算開頭的元音個數
while(right < k) {
vowel += checkVowel(s[right++]);
}
max = vowel; // 指定為目前最大值

while(s[right]) {
vowel = vowel + checkVowel(s[right++]) - checkVowel(s[left++]); // 去頭加尾,一行式寫法
if(max < vowel) { // 存最大值
max = vowel;
if(max == k) // 已達上限,直接離開
break;
}
}
return max;
}

結果二:
結果還不錯哦...



沒有留言:

張貼留言