【发布时间】:2020-12-07 19:48:52
【问题描述】:
我正在对 CodeWars 进行挑战,但遇到了一个奇怪的错误。这是问题陈述:
给定一串单词,你需要找到得分最高的单词。单词的每个字母根据其在字母表中的位置得分:a = 1、b = 2、c = 3 等。您需要将得分最高的单词作为字符串返回。如果两个单词得分相同,则返回原始字符串中出现最早的单词。所有字母均为小写,所有输入均有效。
这是我写的在某些情况下不起作用的算法:
public static String high(String s) {
String[] words = s.split(" ");
int[] scores = new int[words.length];
for (int j = 0; j < words.length; j++) {
for (int i = 0; i < words[j].length(); i++) {
scores[j] += (int) words[j].charAt(i);
}
}
int highestWordIndex = 0;
for (int i = 1; i < words.length; i++) {
if (scores[i] > scores[highestWordIndex]) highestWordIndex = i;
}
return words[highestWordIndex];
}
但是,当我在嵌套的 for 循环中添加“- 96”时,它可以工作。这是代码:
public static String high(String s) {
String[] words = s.split(" ");
int[] scores = new int[words.length];
for (int j = 0; j < words.length; j++) {
for (int i = 0; i < words[j].length(); i++) {
scores[j] += (int) words[j].charAt(i) - 96;
}
}
int highestWordIndex = 0;
for (int i = 1; i < words.length; i++) {
if (scores[i] > scores[highestWordIndex]) highestWordIndex = i;
}
return words[highestWordIndex];
}
知道为什么会有所作为吗?
【问题讨论】: