File tree 1 file changed +26
-18
lines changed
scripts/algorithms/M/Maximum Number of Vowels in a Substring of Given Length
1 file changed +26
-18
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 7 ms (Top 97.98%) | Memory: 45.20 MB (Top 9.52%)
2
+
1
3
class Solution {
2
4
public int maxVowels (String s , int k ) {
3
- int max =0 ,cnt =0 ;
4
- for (int i =0 ,j =0 ;j <s .length ();j ++){
5
- if (j -i +1 <k ){
6
- if (s .charAt (j )=='a' ||s .charAt (j )=='e' || s .charAt (j )=='i' || s .charAt (j )=='o' || s .charAt (j )=='u' ){
7
- cnt ++;
8
- }
9
- }
10
- else {
11
- if (s .charAt (j )=='a' ||s .charAt (j )=='e' || s .charAt (j )=='i' || s .charAt (j )=='o' || s .charAt (j )=='u' ){
12
- cnt ++;
13
- }
14
- max =Math .max (max ,cnt );
15
- if (s .charAt (i )=='a' ||s .charAt (i )=='e' || s .charAt (i )=='i' || s .charAt (i )=='o' || s .charAt (i )=='u' ){
16
- cnt --;
17
- }
18
- i ++;
5
+ int n = s .length ();
6
+ int maxVowels = 0 ;
7
+ int count = 0 ;
8
+
9
+ int [] vowels = new int [128 ];
10
+ vowels ['a' ] = 1 ;
11
+ vowels ['e' ] = 1 ;
12
+ vowels ['i' ] = 1 ;
13
+ vowels ['o' ] = 1 ;
14
+ vowels ['u' ] = 1 ;
15
+
16
+ for (int i = 0 ; i < k ; i ++) {
17
+ count += vowels [s .charAt (i )];
18
+ }
19
+
20
+ maxVowels = count ;
21
+ for (int i = k ; i < n ; i ++) {
22
+ count += vowels [s .charAt (i )] - vowels [s .charAt (i - k )];
23
+ maxVowels = Math .max (maxVowels , count );
24
+ //System.out.println(Arrays.toString(vowels));
25
+ if (maxVowels == k ) {
26
+ return maxVowels ;
19
27
}
20
-
21
28
}
22
- return max ;
29
+ return maxVowels ;
23
30
}
24
31
}
32
+
You can’t perform that action at this time.
0 commit comments