LeetCode 75
Maximum Number of Vowels in a Substring
- Problem
- LC 1456
- Topic
- Sliding Window
- File
- official75_LC1456MaximumNumberOfVowelsInSubstring.java
- Path
- pkg5leetcode/official75/official75_LC1456MaximumNumberOfVowelsInSubstring.java
- Package
- pkg5leetcode.official75
- Command
- java pkg5leetcode/official75/official75_LC1456MaximumNumberOfVowelsInSubstring.java
- Approach
- Sliding window count vowels up to size k.
- Complexity
- Time O(n), Space O(1)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.official75;2 3/*4 * Maximum Number of Vowels in a Substring | LC 14565 * APPROACH: Sliding window count vowels up to size k.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class official75_LC1456MaximumNumberOfVowelsInSubstring {9 static boolean isVowel(char c) {10 return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';11 }12 13 static int maxVowels(String s, int k) {14 int count = 0, best = 0;15 for (int i = 0; i < s.length(); i++) {16 if (isVowel(s.charAt(i))) count++;17 if (i >= k && isVowel(s.charAt(i - k))) count--;18 if (i >= k - 1) best = Math.max(best, count);19 }20 return best;21 }22 23 public static void main(String[] args) {24 check(maxVowels("abciiidef", 3) == 3, "case1");25 check(maxVowels("leetcode", 3) == 2, "case2");26 System.out.println("all tests passed");27 }28 29 static void check(boolean cond, String name) {30 if (!cond) throw new AssertionError("FAILED: " + name);31 System.out.println(" PASS " + name);32 }33}