Find the Longest Vowel Substring in Java
The challenge
The vowel substrings in the word codewarriors are o, e, a, io. The longest of these has a length of 2.
Given a lowercase string that has alphabetic characters only (both vowels and consonants) and no spaces, return the length of the longest vowel substring. Vowels are any of aeiou.
Examples:
"codewarriors" → 2 (the "io" in warriors)
"suoidea" → 3 (the "uoi")
"aeioaexaeuoiou" → 5 (the "aeioa" at the start... wait, no — "euoiou" = 6? Let's trace it)
Solution 1: single pass with counter
Track the current vowel run length and update the maximum:
public class Vowels {
public static int solve(String s) {
int max = 0;
int current = 0;
String vowels = "aeiou";
for (char c : s.toCharArray()) {
if (vowels.indexOf(c) >= 0) {
current++;
max = Math.max(max, current);
} else {
current = 0;
}
}
return max;
}
}
How it works: Walk through each character. If it’s a vowel, increment the counter. If not, reset to zero. Track the maximum seen. O(n) time, O(1) space.
Solution 2: regex approach
import java.util.regex.*;
public class Vowels {
public static int solve(String s) {
int max = 0;
Matcher m = Pattern.compile("[aeiou]+").matcher(s);
while (m.find()) {
max = Math.max(max, m.group().length());
}
return max;
}
}
Finds all consecutive vowel sequences and returns the length of the longest one.
Solution 3: stream-based (Java 8+)
import java.util.Arrays;
public class Vowels {
public static int solve(String s) {
return Arrays.stream(s.split("[^aeiou]+"))
.mapToInt(String::length)
.max()
.orElse(0);
}
}
Split on non-vowel characters, then find the longest resulting segment.
Test cases
assertEquals(2, Vowels.solve("codewarriors"));
assertEquals(3, Vowels.solve("suoidea"));
assertEquals(0, Vowels.solve("bcd"));
assertEquals(1, Vowels.solve("a"));
assertEquals(5, Vowels.solve("aeiou"));
Same puzzle, other languages
- Longest vowel substring — Python — single-pass Python solution.
- Longest vowel substring — JavaScript — JS solution using
Setfor vowel lookup.
Related challenges
If you liked this substring problem, try these:
- Longest substring in alphabetical order (Python) — same “track the longest run” pattern, but checking alphabetical order instead of vowels.
- Find all permutations of a string (Python) — a classic string manipulation challenge using recursion.