[英]Is there a difference in terms of algorithm efficiency between subtracting ASCII values and simply subtracting an integer?
我最近完成了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)時間中運行。
給定一個僅包含從A到Z的大寫字母的字符串,A = 1,B = 2,等等,Z = 26。
鑒於該問題陳述,這一行
word = word.replaceAll("\\s+","");
是沒有用的,並且無意義地遍歷整個String
值。
兩者total += (int)word.charAt(i)-64;
和total += word.charAt(i)-'A'+1;
會幾乎同樣快地運行。 問題出在這里:
word = word.replaceAll("\\s+","");
該行(僅在您的代碼中)使您的程序變慢。 正如您在其他響應中看到的那樣,此行是不必要的。
這個
total += word.charAt(i) - 64;
與...完全相同
total += (int) word.charAt(i) - 64;
這與
total += word.charAt(i) - 'A' + 1;
如果您想加快程序速度,請不要使用正則表達式
public int write(String word) {
int total = 0;
for(int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (ch >= 'A')
total += word.charAt(i) - 64;
}
return total;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.