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 * 105
-
word
consists of characters'a'
,'e'
,'i'
,'o'
, and'u'
.
所有元音按顺序排布的最长子字符串。
当一个字符串满足如下条件时,我们称它是 美丽的 :
所有 5 个英文元音字母('a' ,'e' ,'i' ,'o' ,'u')都必须 至少 出现一次。
这些元音字母的顺序都必须按照 字典序 升序排布(也就是说所有的 'a' 都在 'e' 前面,所有的 'e' 都在 'i' 前面,以此类推)
比方说,字符串 "aeiou" 和 "aaaaaaeiiiioou" 都是 美丽的 ,但是 "uaeio" ,"aeoiu" 和 "aaaeeeooo" 不是美丽的 。给你一个只包含英文元音字母的字符串 word ,请你返回 word 中 最长美丽子字符串的长度 。如果不存在这样的子字符串,请返回 0 。
子字符串 是字符串中一个连续的字符序列。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-of-all-vowels-in-order
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这道题的题设比较明显,我这里给出滑动窗口的做法。这道题唯一需要注意的是当我们发现当前字母的字典序小于之前一个字母的时候,就说明需要重新从 a 开始看了,此时不要忘记如果当前字母是 a 的话,需要将其加入hashset。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public int longestBeautifulSubstring(String word) { 3 HashSet<Character> set = new HashSet<>(); 4 Character prev = 'a'; 5 int start = 0; 6 int end = 0; 7 int res = 0; 8 while (end < word.length()) { 9 if (word.charAt(end) < prev) { 10 set.clear(); 11 start = end; 12 if (word.charAt(end) == 'a') { 13 set.add(word.charAt(end)); 14 } 15 } else { 16 set.add(word.charAt(end)); 17 if (set.size() == 5) { 18 res = Math.max(res, end - start + 1); 19 } 20 } 21 prev = word.charAt(end); 22 end++; 23 } 24 return res; 25 } 26 }