A Greedy Sliding Window Approach
Intuition\nThe problem requires finding the longest contiguous substring in which all five vowels (a, e, i, o, u) appear at least once in alphabetical order. Th
# Intuition\nThe problem requires finding the longest contiguous substring in which all five vowels (a, e, i, o, u) appear at least once in alphabetical order. The key observation is that as soon as the order is violated, we need to reset the tracking of the current valid substring.\n\n# Approach\n1. Initialization:\n\n- Use a list vowels to represent the required order of vowels.\n- Initialize pointers and counters: i for iterating through the string, curr_idx to track the current vowel in the sequence, count to count the length of the current valid substring, and ans to store the maximum length of any valid substring found.\n\n2. Iterating through the string:\n\n- For each character in the string, check if it matches the current vowel in the sequence (vowels[curr_idx]).\n- If it matches, increment the count.\n- If the current character does not match but the previous character matched the current vowel, and the current character matches the next vowel in sequence, move to the next vowel and increment count.\n- If neither condition is met, check if the current substring is a valid "beautiful" substring by verifying that all vowels were seen (curr_idx == len(vowels) - 1). If so, update ans with the maximum length. Then reset the curr_idx and count and restart the process.\n- After the loop, check again if the last valid substring is the longest one.\n\n3. Return the result:\n- Return the maximum length found.\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution:\n    def longestBeautifulSubstring(self, word: str) -> int:\n        vowels = [\'a\', \'e\', \'i\', \'o\', \'u\']\n        i = 0\n        curr_idx = 0\n        count = 0\n        ans = 0\n        while i < len(word):\n            if word[i] == vowels[curr_idx]:\n                count += 1\n            elif (i > 0 \n                and word[i - 1] == vowels[curr_idx]\n                and curr_idx < len(vowels) - 1 \n                and word[i] == vowels[curr_idx + 1]):\n                curr_idx += 1\n                count += 1\n            else:\n                if curr_idx == len(vowels) - 1:\n                    ans = max(ans, count)\n                curr_idx = 0\n                count = 0\n                if word[i] == vowels[curr_idx]:\n                    count += 1\n            i += 1\n\n        if curr_idx == len(vowels) - 1:\n            ans = max(ans, count)\n        \n        return ans\n\n\n            \n        \n```
['String', 'Greedy', 'Sliding Window', 'Python3']