Get the Consonant Value in Java

1 min read 298 words

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.

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

Option 2:

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

Option 3:

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

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