A string is considered beautiful if it satisfies the following conditions:
'a'
, 'e'
, 'i'
, 'o'
, 'u'
) must appear at least once in it.'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.
Example 1:
Input: word = "aeiaaioaaaaeiiiiouuuooaauuaeiu" Output: 13 Explanation: The longest beautiful substring in word is "aaaaeiiiiouuu" of length 13.
Example 2:
Input: word = "aeeeiiiioooauuuaeiou" Output: 5 Explanation: The longest beautiful substring in word is "aeiou" of length 5.
Example 3:
Input: word = "a" Output: 0 Explanation: There is no beautiful substring, so return 0.
Constraints:
1 <= word.length <= 5 * 105
word
consists of characters 'a'
, 'e'
, 'i'
, 'o'
, and 'u'
.struct Solution;
impl Solution {
fn longest_beautiful_substring(word: String) -> i32 {
let word: Vec<char> = word.chars().collect();
let vowels: Vec<char> = vec!['a', 'e', 'i', 'o', 'u'];
let mut start = 0;
let n = word.len();
let mut res = 0;
'outer: while start < n {
while start < n && word[start] != 'a' {
start += 1;
}
let mut end = start;
for i in 0..5 {
if !(end < n && word[end] == vowels[i]) {
start = end;
continue 'outer;
}
while end < n && word[end] == vowels[i] {
end += 1;
}
}
res = res.max(end - start);
start = end;
}
res as i32
}
}
#[test]
fn test() {
let word = "aeiaaioaaaaeiiiiouuuooaauuaeiu".to_string();
let res = 13;
assert_eq!(Solution::longest_beautiful_substring(word), res);
let word = "aeeeiiiioooauuuaeiou".to_string();
let res = 5;
assert_eq!(Solution::longest_beautiful_substring(word), res);
let word = "a".to_string();
let res = 0;
assert_eq!(Solution::longest_beautiful_substring(word), res);
}