Longest vowel chain in Java

1 min read 200 words

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);
  }
}

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;
  }
}

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;
  }
}

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"));
    }
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts