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 楼答案
鉴于问题陈述,这条线
是无用的,并且无意义地迭代整个
String
值