繁体   English   中英

Java:查找具有最高值的字符串

[英]Java: Find String with the highest value

我需要接受一个字符串作为输入,将其拆分为单个单词的数组(在“”上拆分),并将得分最高的单词作为字符串返回。 一个单词的每个字母都会根据其在字母表中的位置来给分数打分:a = 1,b = 2,c = 3等等。如果两个单词得分相同,我将返回最早出现在原始字符串中的单词。 所有字母均为小写,所有输入均有效。

首先,我决定是根据上面指定的字符串总值对字符串评分还是仅使用ascii值对字符串进行评分,结果都是相同的。 因此,我选择使用ascii值使事情更简单。 我将每个单词变成一个字符数组,然后循环以求和。 然后,我将单词和总数放入Hashmap中。 下一部分我会继续讲下去。 如何遍历哈希图以找到最大值,然后获取关联的单词? 这是来自代码kata网站的kate。 我可以自由使用我选择解决的任何方式。 所以我不喜欢哈希图的想法。

有什么建议吗?

到目前为止,这是我的代码:

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

使用java8

key = Collections.max(map.entrySet(), Map.Entry.comparingByValue()).getKey();      

System.out.println("Key : "+key+ " Maximum value : "+map.get(key));

如果您不关心其他字符串,即,如果找到了新的高分单词并且仅需要最高价值的字符串,那么它们就毫无价值,那么哈希映射就显得过分了。 继续逐个单词遍历输入单词并给每个单词评分,如果您发现得分较高的单词,请更新输出,否则请继续操作直至结尾。

另外,如果您需要将所有字符串与分数保持在一起,则:为了使单词随单词一起获得最大值,您可以使用优先队列(即最大堆)来对单词的分数进行堆放。 创建一个单词和分数对并将其插入优先级队列。

注意:您将必须为队列编写一个比较器。

其次,使用这种方法,每次提取字符串时都会得到排序的输出。

这样的事情应该工作

Entry<String,Integer> maxTerm = null;

for(Entry<String,Integer> entry : hashMap.entrySet()) {

    if (maxTerm == null || entry.getValue() > maxTerm.getValue()) {
        maxTerm = entry;
    }
}

String wordFound = maxTerm.getKey();
int wordScore = maxTerm.getValue();

因此,您遍历哈希图,获取每个条目,如果条目的值大于任何先前的值,则获取条目,然后可以从中收集值和键,并根据需要使用。

使用Java8,

import static java.util.Arrays.stream; import static java.util.Comparator.comparing; /* * Method to return highest scored word(which is defined * as sum of ASCII value of alphabets in word). * In case no word is present, Empty String is returned. */

public static String high(String s) {
    return stream(s.split("\\W+"))
            .max(comparing(str -> str.chars().sum()))
            .orElse("");
}

`

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM