有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java减去ASCII值和简单地减去整数在算法效率方面有什么不同吗?

我最近完成了TopCoder算法竞赛单轮比赛618,问题很简单。给定一个仅由a到Z、a=1、B=2等大写字母和Z=26组成的字符串。目标是使用这些值返回字符串的总值

这是我的算法:

public class WritingWords {
  public int write(String word) {
    int total = 0;
    word = word.replaceAll("\\s+","");

    for(int i = 0; i < word.length(); i++){
      total += (int)word.charAt(i)-64;
    }

    return total;
  }
}

我的分数是165分/250分

这是另一个获得249/250的用户的代码:

public class WritingWords {
  public int write(String word) {
    int total = 0;

    for(int i = 0; i < word.length(); i++){
      total += word.charAt(i)-'A'+1;
    }

    return total;
  }
}

对我来说,这两个源代码看起来非常相似,我不确定为什么我会得到这么低的分数。是什么原因导致后一种算法比我的算法效率更高?在我看来,不管怎样,他们都会在O(n)时间里跑


共 (1) 个答案

  1. # 1 楼答案

    Given a string consisting only of capital letters from A to Z, A = 1, B = 2, etc. and Z = 26.

    鉴于问题陈述,这条线

    word = word.replaceAll("\\s+","");
    

    是无用的,并且无意义地迭代整个String