【问题标题】:Highest Scoring Word algorithm throwing quirky error最高得分词算法抛出古怪错误
【发布时间】: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];
}

知道为什么会有所作为吗?

【问题讨论】:

    标签: java algorithm ascii


    【解决方案1】:

    'a' 是十六进制 0x61,或十进制 97。所以当您使用 -96 时,您使用的是正确的计算。我会做以下之一:

    score += charAt() - 0x60;
    

    int offset = ('a' - 1);
    ...
    score += charAt() - offset;
    

    对于相同长度的单词,这不会产生影响,但是当单词长度不同时,超过 96 的附加点会使结果偏向更长的单词。

    【讨论】:

      【解决方案2】:

      之所以能减96,是因为ASCII中小写字符的十进制值是从97开始的。比如ASCII中的“a”是97,所以97-96=1,如题。

      ASCII Chart for reference

      【讨论】:

        【解决方案3】:

        'a' 的 (int) char 版本是 97,'b' 是 98,'c' 是 99,依此类推。该问题要求您将这些转换为 1,2,3,... 有充分的理由。 考虑一下 cab 这个词和 ox 这个词。

        “cab”应该是 3 + 1 + 2 = 6。但是在你的实现中它是 99+97+98=294

        “ox”应该是 15 + 24 = 39。但是在你的实现中它是 111 + 120 = 231

        “ox”应该比“cab”得分高,但这不是因为你将你的字符转换为他们的 ascii 代表整数,而不是问题所问的 1-26。因此,您的算法会为较长的单词提供更多的分数,因为每个额外的字符会比根据问题应该得到的分数高出 96 分。减去 96 会将您的分数域从 97-122 降到 1-26,从而为您解决了这个问题。

        希望这有帮助:)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-05-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-28
          • 2011-10-08
          • 1970-01-01
          • 2017-07-25
          相关资源
          最近更新 更多