#1839
Medium Algorithms Longest substring of all vowels in order
String Sliding Window
51.6% acceptance
Feb 25, 2026
850
31
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.).
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.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn longest_beautiful_substring(word: String) -> i32 {
let bytes = word.as_bytes();
let n = bytes.len();
let mut result = 0;
let mut i = 0;
while i < n {
if bytes[i] != b'a' { i += 1; continue; }
let start = i;
let mut distinct = 1;
i += 1;
while i < n && bytes[i] >= bytes[i-1] {
if bytes[i] > bytes[i-1] { distinct += 1; }
i += 1;
}
if distinct == 5 {
result = result.max(i - start);
}
}
result as i32
}
}