简体   繁体   English

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

[英]Java: Find String with the highest value

I need to accept a string as input, split it into an array of individual words ( split on " ") and return the highest scoring word as a string. 我需要接受一个字符串作为输入,将其拆分为单个单词的数组(在“”上拆分),并将得分最高的单词作为字符串返回。 Each letter of a word scores points according to it's position in the alphabet: a = 1, b = 2, c = 3 etc. If two words score the same, I'll return the word that appears earliest in the original string. 一个单词的每个字母都会根据其在字母表中的位置来给分数打分:a = 1,b = 2,c = 3等等。如果两个单词得分相同,我将返回最早出现在原始字符串中的单词。 All letters will be lowercase and all inputs will be valid. 所有字母均为小写,所有输入均有效。

First, I decided that whether I score a string based on its total value as specified above, or simply use the ascii value, the result will be the same. 首先,我决定是根据上面指定的字符串总值对字符串评分还是仅使用ascii值对字符串进行评分,结果都是相同的。 So I choose to use the ascii value to make things simpler. 因此,我选择使用ascii值使事情更简单。 I turn each word into a character array and the loop through to sum the total. 我将每个单词变成一个字符数组,然后循环以求和。 Then I put the word and the total into a Hashmap. 然后,我将单词和总数放入Hashmap中。 The next part I'm stuck on. 下一部分我会继续讲下去。 How do I loop through the hashmap to find the largest value and then grab the associated word? 如何遍历哈希图以找到最大值,然后获取关联的单词? This is a kate from a code kata site. 这是来自代码kata网站的kate。 I'm free to use whatever means I choose to solve it. 我可以自由使用我选择解决的任何方式。 So I'm not married to the hashmap idea. 所以我不喜欢哈希图的想法。

Suggestions? 有什么建议吗?

Here is my code thus far: 到目前为止,这是我的代码:

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

try this 尝试这个

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

With java8 使用java8

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

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

If you do not care about the other strings, ie they are of no value if a new high score word is found and only need the highest valued string, hashmap is an overkill. 如果您不关心其他字符串,即,如果找到了新的高分单词并且仅需要最高价值的字符串,那么它们就毫无价值,那么哈希映射就显得过分了。 Keep traversing the input word by word and scoring each word, if you find a word with a higher score, update your output, otherwise continue till the end. 继续逐个单词遍历输入单词并给每个单词评分,如果您发现得分较高的单词,请更新输出,否则请继续操作直至结尾。

Also, if you need to keep all the strings with their score then: In order to get the maximum value word along with the word, you can use a Priority Queue (ie a max heap) that heapify on the score of the word. 另外,如果您需要将所有字符串与分数保持在一起,则:为了使单词随单词一起获得最大值,您可以使用优先队列(即最大堆)来对单词的分数进行堆放。 Create a pair of word and score and insert it into priority queue. 创建一个单词和分数对并将其插入优先级队列。

Note: you will have to write a comparator for the queue. 注意:您将必须为队列编写一个比较器。

Secondly, with this approach, you will get sorted output each time you extract the string. 其次,使用这种方法,每次提取字符串时都会得到排序的输出。

Something like this should work 这样的事情应该工作

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

So you iterate through the hashmap, grabbing each entry, and if the entry has a value that is greater than any previous, you grab the Entry and you can gather the value and key from it, and use as you wish. 因此,您遍历哈希图,获取每个条目,如果条目的值大于任何先前的值,则获取条目,然后可以从中收集值和键,并根据需要使用。

Using Java8, 使用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