我需要接受一个字符串作为输入,将其拆分为单个单词的数组(拆分为 ""),然后将得分最高的单词作为字符串返回。单词的每个字母根据其在字母表中的位置得分:a = 1、b = 2、c = 3 等。如果两个单词得分相同,我将返回在原始字符串中最早出现的单词。所有字母均为小写,所有输入均有效。
首先,我决定无论是根据上面指定的总值对字符串进行评分,还是只使用 ascii 值,结果都是一样的。所以我选择使用 ascii 值来使事情更简单。我将每个单词变成一个字符数组,然后循环计算总和。然后我把这个词和总数放到一个Hashmap中。我坚持的下一部分。如何遍历 hashmap 以找到最大值,然后获取关联的词?这是来自代码型网站的凯特。我可以自由使用我选择的任何方式来解决它。所以我不接受 hashmap 的想法。
建议?
到目前为止,这是我的代码:
public static String high(String s) {
// Your code here...
HashMap<String, Integer> map = new HashMap<String, Integer>();
String[] words = s.split(" ");
// loop through all of the words, for each word get its value
// and insert the word into map as key, value as that keys value
for(int i = 0; i < words.length; i++) {
char[] tempWordChars = words[i].toCharArray();
int total = 0;
for(int j = 0; j < tempWordChars.length; j++) {
total = total + (int)tempWordChars[j];
}
map.put(tempWordChars.toString(), total);
}
return "";
}
最佳答案
试试这个
public static String high(String s) {
String[] words = s.split(" ");
int max = 0;
String sToReturn = null;
for (String word : words) {
char[] tempWordChars = word.toCharArray();
int total = 0;
for (int j = 0; j < tempWordChars.length; j++) {
total = total + (int) tempWordChars[j];
}
if (total > max) {
sToReturn = word;
max=total;
}
}
return sToReturn;
}
关于Java:查找具有最高值的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46518977/