# 1839. Longest Substring Of All Vowels in Order ###### tags: `Leetcode` `Medium` `Sliding Window` Link: https://leetcode.com/problems/longest-substring-of-all-vowels-in-order/ ## 思路 $O(N)$ $O(1)$ ### 思路一 非常直觉的做法,但是需要考虑的情况有点多 用回圈检查, - 如果这个字母是正确的,把后面所有重复的都用while回圈扫过一遍,下一次再进for loop的时候就检查元音表里的下一个元音 - 如果这个字母是不正确的,例如aeu, aeia, 就说明之前的要作废啦,如果这个错的字母是a,就说明要重新计数,所以让下一次进入for回圈的i还是指向a,因此需要i--,并且把len设为0,(这里不论错的字母是不是a都要设) - 如果元音表已经检查完了,也就是```vIdx==vowels.length```,就说明现在的长度是valid,可以进行比较 ### 思路二 参考[这里](https://leetcode.com/problems/longest-substring-of-all-vowels-in-order/discuss/1175189/Best-C%2B%2B-Solution) Given word only contains vowels(given in question) and we just have to find out the longest substring that contains all vowels in sorted order of ascii value. i.e 'a'<'e'<'i'<'o'<'u' . So if a substring have 5 unique character and following ascii order we can update our answer by its length. ## Code ### 思路一 ```java= class Solution { public int longestBeautifulSubstring(String word) { int len = 0; int maxLen = 0; char[] vowels = new char[]{'a','e','i','o','u'}; int vIdx = 0; for(int i = 0;i < word.length();i++){ if(word.charAt(i)==vowels[vIdx]){ while(i < word.length() && word.charAt(i)==vowels[vIdx]){ i++; len++; } i--; vIdx++; } // start check from beginning vowel else{ vIdx = 0; if(word.charAt(i)==vowels[0]) i--; len = 0; } if(vIdx == vowels.length){ maxLen = Math.max(len, maxLen); vIdx = 0; len = 0; } } return maxLen; } } ``` ### 思路二 ```java= public int longestBeautifulSubstring(String word) { int cnt=1, len=1, max_length=0; int n=word.length(); for(int i=1;i<n;i++){ if(word.charAt(i)==word.charAt(i-1)){ len++; }else if(word.charAt(i-1)<word.charAt(i)){ cnt++; len++; }else{ len=1; cnt=1; } if(cnt==5){ max_length=Math.max(max_length,len); } } return max_length; } ```