[LeetCode] Longest Substring Of All Vowels in Order

1839. Longest Substring Of All Vowels in Order

A string is considered beautiful if it satisfies the following conditions:

  • Each of the 5 English vowels (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) must appear at least once in it.
  • The letters must be sorted in alphabetical order (i.e. all ‘a’s before ‘e’s, all ‘e’s before ‘i’s, etc.).

For example, strings “aeiou” and “aaaaaaeiiiioou” are considered beautiful, but “uaeio”, “aeoiu”, and “aaaeeeooo” are not beautiful.

Given a string word consisting of English vowels, return the length of the longest beautiful substring of word. If no such substring exists, return 0.

A substring is a contiguous sequence of characters in a string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
int longestBeautifulSubstring(string word) {
int len = word.length();
if(len == 1) return 0;
int res = 0, front = 0, end = 0;
bool chk[5]{0,0,0,0,0};
while(end < len) {
switch (word[end]) {
case 'a': chk[0] = true; break;
case 'e': chk[1] = true; break;
case 'i': chk[2] = true; break;
case 'o': chk[3] = true; break;
case 'u': chk[4] = true; break;
}
if(end + 1 == len || word[end] > word[end + 1]) {
if(chk[0] && chk[1] && chk[2] && chk[3] && chk[4])
res = max(res, end - front + 1);
front = end + 1;
memset(chk, false, sizeof(chk));
}
end++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/04/25/PS/LeetCode/longest-substring-of-all-vowels-in-order/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.