Longest Substring Of All Vowels in Order Problem
Description
LeetCode Problem 1839.
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.
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 * 10^5wordconsists of characters'a','e','i','o', and'u'.
Solution
Approach: Group Equal Letters
Compress word into runs of equal letters, each stored as a pair (letter, run length). A beautiful substring must be made of five consecutive runs whose letters are exactly a, e, i, o, u in that order, and the best one starting at any run uses the whole runs (longer is always better).
Check each window of five consecutive runs. If the letters spell aeiou, its length is the sum of the five run lengths; keep the maximum, or 0 if no window qualifies.
Complexity: O(n) time and O(n) space for the runs.
class Solution:
def longestBeautifulSubstring(self, word: str) -> int:
arr = []
n = len(word)
i = 0
while i < n:
j = i
while j < n and word[j] == word[i]:
j += 1
arr.append((word[i], j - i))
i = j
ans = 0
for i in range(len(arr) - 4):
a, b, c, d, e = arr[i : i + 5]
if a[0] + b[0] + c[0] + d[0] + e[0] == "aeiou":
ans = max(ans, a[1] + b[1] + c[1] + d[1] + e[1])
return ans