Python Intuitive State Machine
Intuition\n Describe your first thoughts on how to solve this problem. \nTrack what state we are in when building the current substring. Then update the maximum
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTrack what state we are in when building the current substring. Then update the maximum length if our current state matches the conditions for a beautiful substring.\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nState 0 is an invalid state (for example, current substring from $$l$$ to $$i$$ is not in alphabetical order)\nState 1 is last character of current susbtring is $$a$$ and current substring is in alphabetical order. Set $$l$$ to this position if it is the first $$a$$ in the current substring\nState 2 is last character of current susbtring is $$e$$ and current substring is in alphabetical order\nState 3 is last character of current susbtring is $$i$$ and current substring is in alphabetical order\nState 4 is last character of current susbtring is $$o$$ and current substring is in alphabetical order\nState 5 is last character of current susbtring is $$u$$ and current substring is in alphabetical order. Update the max length if current substring has largest length\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nimport collections\n\nclass Solution:\n    def longestBeautifulSubstring(self, word: str) -> int:\n        n = len(word)\n        if n < 5:\n            return 0\n\n        max_len = 0\n        l = 0\n        state = 0\n        for i, ch in enumerate(word):\n            if state != 1 and ch == "a":\n                state = 1\n                l = i\n            elif state == 1 and ch == "a":\n                state = 1\n            elif (state == 1 or state == 2) and ch == "e":\n                state = 2\n            elif (state == 2 or state == 3) and ch == "i":\n                state = 3\n            elif (state == 3 or state == 4) and ch == "o":\n                state = 4\n            elif (state == 4 or state == 5) and ch == "u":\n                state = 5\n                max_len = max(max_len, i - l + 1)\n            else:\n                state = 0\n\n        return max_len\n```
['Python3']