Skip to content

Longest vowel chain 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.

The solution in Java code

Option 1:

import static; interface Solution { static int solve(String s) { return of(s.split("[^aeiou]")).mapToInt(String::length).max().orElse(); } }
Code language: Java (java)

Option 2:

import java.util.ArrayList; class Solution{ public static int solve(String s){ var vowels = new ArrayList<Character>(); vowels.add('a'); vowels.add('e'); vowels.add('i'); vowels.add('o'); vowels.add('u'); var arr = s.toCharArray(); int max = ; int counter = ; for (int i = ; i < arr.length ; i++) { if (vowels.contains(arr[i])){ counter++; }else{ if (counter>max){ max = counter; } counter = ; } } if (counter>max){ max = counter; } return max; } }
Code language: Java (java)

Option 3:

class Solution{ public static int solve(String s){ //.. String[] vowelsTable = s.split("[bcdfghjklmnpqrstvwxyz]"); int longuestVowelSubString = ; for (String mySubString: vowelsTable){ if (mySubString.length()>longuestVowelSubString){ longuestVowelSubString = mySubString.length(); } } return longuestVowelSubString; } }
Code language: Java (java)

Test cases to validate our solution

import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest{ @Test public void basicTests(){ assertEquals(3,Solution.solve("ultrarevolutionariees")); assertEquals(2,Solution.solve("codewarriors")); assertEquals(3,Solution.solve("suoidea")); assertEquals(1,Solution.solve("strengthlessnesses")); assertEquals(11,Solution.solve("mnopqriouaeiopqrstuvwxyuaeiouaeiou")); } }
Code language: Java (java)

See also  Maximum Different of Int-Array in Java
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x