LeetCode-in-Java

1839. Longest Substring Of All Vowels in Order

Medium

A string is considered beautiful if it satisfies the following conditions:

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:

Solution

public class Solution {
    public int longestBeautifulSubstring(String word) {
        int cnt = 1;
        int len = 1;
        int maxLen = 0;
        for (int i = 1; i != word.length(); ++i) {
            if (word.charAt(i - 1) == word.charAt(i)) {
                ++len;
            } else if (word.charAt(i - 1) < word.charAt(i)) {
                ++len;
                ++cnt;
            } else {
                cnt = 1;
                len = 1;
            }

            if (cnt == 5) {
                maxLen = Math.max(maxLen, len);
            }
        }
        return maxLen;
    }
}