Skip to content

Get the Consonant Value in Java

The challenge

Given a lowercase string that has alphabetic characters only and no spaces, return the highest value of consonant substrings. Consonants are any letters of the alphabet except "aeiou".

We shall assign the following values: a = 1, b = 2, c = 3, .... z = 26.

For example, for the word “zodiacs”, let’s cross out the vowels. We get: “z o d ia cs”

-- The consonant substrings are: "z", "d" and "cs" and the values are z = 26, d = 4 and cs = 3 + 19 = 22. The highest is 26. solve("zodiacs") = 26 For the word "strength", solve("strength") = 57 -- The consonant substrings are: "str" and "ngth" with values "str" = 19 + 20 + 18 = 57 and "ngth" = 14 + 7 + 20 + 8 = 49. The highest is 57.
Code language: JavaScript (javascript)

The solution in Java code

Option 1:

import java.util.stream.*; import java.util.*; public class ConsonantValue { public static int solve(final String s) { return Arrays.stream(s.split("[aeiou]+")) .mapToInt(t->t.chars().sum()-t.length()*96) .max() .getAsInt(); } }
Code language: Java (java)

Option 2:

public class ConsonantValue { public static int solve(final String s) { int sum = , maxsum = ; char[] arr = s.toCharArray(); for (char c : arr) { if ("aeiou".indexOf(c)>=) sum = ; else { sum += c-'a'+1; maxsum = Math.max(sum, maxsum); } } return maxsum; } }
Code language: Java (java)

Option 3:

class ConsonantValue { static int solve(String s) { int max = ; for (var sil : s.replaceAll("[aeiou]", " ").split(" ")) { int value = sil.chars().map(c -> c - 96).sum(); if (max < value) max = value; } return max; } }
Code language: Java (java)

Test cases to validate our solution

import org.junit.Test; public class SampleTest { @Test public void basicTests() { Tester.doTest("zodiac", 26); Tester.doTest("chruschtschov", 80); Tester.doTest("khrushchev", 38); Tester.doTest("strength", 57); Tester.doTest("catchphrase", 73); Tester.doTest("twelfthstreet", 103); Tester.doTest("mischtschenkoana", 80); } }
Code language: Java (java)

See also  What century is it in Java
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x