|
1 | 1 | package com.fishercoder.solutions.secondthousand; |
2 | 2 |
|
3 | | -import java.util.Arrays; |
4 | | -import java.util.HashMap; |
5 | 3 | import java.util.HashSet; |
6 | | -import java.util.Map; |
7 | 4 | import java.util.Set; |
8 | 5 |
|
9 | 6 | public class _1456 { |
10 | 7 | public static class Solution1 { |
11 | 8 | public int maxVowels(String s, int k) { |
12 | | - Map<Character, Integer> vowels = new HashMap<>(); |
13 | | - Set<Character> set = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u')); |
14 | | - int left = 0; |
15 | | - for (; left < k; left++) { |
16 | | - if (set.contains(s.charAt(left))) { |
17 | | - vowels.put(s.charAt(left), vowels.getOrDefault(s.charAt(left), 0) + 1); |
| 9 | + Set<Character> set = new HashSet<>(); |
| 10 | + set.add('a'); |
| 11 | + set.add('e'); |
| 12 | + set.add('i'); |
| 13 | + set.add('o'); |
| 14 | + set.add('u'); |
| 15 | + int max = Integer.MIN_VALUE; |
| 16 | + int i = 0; |
| 17 | + int vowels = 0; |
| 18 | + for (; i < k; i++) { |
| 19 | + if (set.contains(s.charAt(i))) { |
| 20 | + vowels++; |
18 | 21 | } |
19 | 22 | } |
20 | | - int max = 0; |
21 | | - for (char c : vowels.keySet()) { |
22 | | - max += vowels.get(c); |
23 | | - } |
24 | | - int right = left; |
25 | | - left = 0; |
26 | | - for (; right < s.length(); right++, left++) { |
27 | | - char leftChar = s.charAt(left); |
28 | | - if (set.contains(leftChar) |
29 | | - && vowels.containsKey(leftChar) |
30 | | - && vowels.get(leftChar) > 0) { |
31 | | - vowels.put(leftChar, vowels.get(leftChar) - 1); |
32 | | - } |
33 | | - char rightChar = s.charAt(right); |
34 | | - if (set.contains(rightChar)) { |
35 | | - vowels.put(rightChar, vowels.getOrDefault(rightChar, 0) + 1); |
| 23 | + max = Math.max(max, vowels); |
| 24 | + for (; i < s.length(); i++) { |
| 25 | + if (set.contains(s.charAt(i))) { |
| 26 | + vowels++; |
36 | 27 | } |
37 | | - int thisMax = 0; |
38 | | - for (char c : vowels.keySet()) { |
39 | | - thisMax += vowels.get(c); |
| 28 | + if (set.contains(s.charAt(i - k))) { |
| 29 | + vowels--; |
40 | 30 | } |
41 | | - max = Math.max(max, thisMax); |
| 31 | + max = Math.max(max, vowels); |
42 | 32 | } |
43 | 33 | return max; |
44 | 34 | } |
|
0 commit comments