We want the longest substring containing all five vowels in order, with each vowel appearing at least once and all ‘a’s before ’e’s, all ’e’s before ‘i’s, etc. We can use a sliding window to expand as long as the order is maintained, and reset when the order breaks.
classSolution {
public:int longestBeautifulSubstring(string word) {
int n = word.size(), ans =0, cnt =1, start =0;
for (int i =1; i < n; ++i) {
if (word[i] < word[i-1]) {
cnt =1;
start = i;
} elseif (word[i] > word[i-1]) {
cnt++;
}
if (cnt ==5) ans = max(ans, i - start +1);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
funclongestBeautifulSubstring(wordstring) int {
n, ans, cnt, start:= len(word), 0, 1, 0fori:=1; i < n; i++ {
ifword[i] < word[i-1] {
cnt = 1start = i } elseifword[i] > word[i-1] {
cnt++ }
ifcnt==5 {
ifi-start+1 > ans {
ans = i-start+1 }
}
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
publicintlongestBeautifulSubstring(String word) {
int n = word.length(), ans = 0, cnt = 1, start = 0;
for (int i = 1; i < n; ++i) {
if (word.charAt(i) < word.charAt(i-1)) {
cnt = 1;
start = i;
} elseif (word.charAt(i) > word.charAt(i-1)) {
cnt++;
}
if (cnt == 5) ans = Math.max(ans, i - start + 1);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution {
funlongestBeautifulSubstring(word: String): Int {
val n = word.length
var ans = 0var cnt = 1var start = 0for (i in1 until n) {
if (word[i] < word[i-1]) {
cnt = 1 start = i
} elseif (word[i] > word[i-1]) {
cnt++ }
if (cnt ==5) ans = maxOf(ans, i - start + 1)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
deflongestBeautifulSubstring(self, word: str) -> int:
n = len(word)
ans = cnt =0 start =0for i in range(1, n):
if word[i] < word[i-1]:
cnt =1 start = i
elif word[i] > word[i-1]:
cnt +=1if cnt ==5:
ans = max(ans, i - start +1)
return ans