Highest Scoring Word

Instructions

Given a string of words, you need to find the highest scoring word.

Each letter of a word scores points according to it’s position in the alphabet: a = 1, b = 2, c = 3 etc.

You need to return the highest scoring word as a string.

If two words score the same, return the word that appears earliest in the original string.

All letters will be lowercase and all inputs will be valid.


My Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
import java.util.Arrays;
import java.util.Comparator;

public class HighScoreingWord {
public static String high(String s) {
return Arrays.stream(s.split(" "))
.max(Comparator.comparing(HighScoreingWord::scoreOfWord)).get();
}

public static int scoreOfWord(String word) {
return word.chars().sum() - word.length() * 96;
}
}

Better Solution

1
2
3
4
5
6
7
8
9
10
11
import java.util.Arrays;
import java.util.Comparator;

public class HighScoreingWordSolution {
public static String high(String s) {
return Arrays.stream(s.split(" "))
.max(Comparator.comparingInt(word -> word.chars().map(charr -> charr - 96).sum()))
.get();
}

}

Feeling

아직 제대로 람다를 공부해서 쓰는게 아니다 보니 Comparator를 모르고 있었는데 이번 문제를 통해서 알게되어 좋았다!

지금 읽는 책 다 읽고 나면 바로 자바 8 인 액션 책을 읽어봐야겠다.

Share