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 java.util.stream.Stream.of; interface Solution { static int solve(String s) { return of(s.split("[^aeiou]")).mapToInt(String::length).max().orElse(0); } }
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 = 0; int counter = 0; for (int i = 0; i < arr.length ; i++) { if (vowels.contains(arr[i])){ counter++; }else{ if (counter>max){ max = counter; } counter = 0; } } 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 = 0; 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)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments