題目鏈接,Leetcode1160
心痛的提交過程
你能感受那種,自己在測代碼OK的,但是一提交就錯的心痛感嗎?
絕望中的猜想,迎來勝利的曙光
是不是每次執行solution的時候,並沒有清空Alph呢?
一試,果然如此。
//以下是錯誤解法,錯在將Alph定義爲全局變量
int Alph[26];
int isJizhu(char ** words, int index){
int res = 1;
int beta[26] = {0};
for(int i=0;i<26;i++){
beta[i] = 0;
}
for(int i=0;i<strlen(words[index]);i++){
beta[words[index][i] - 'a']++;
}
for(int i=0;i<26;i++){
if(beta[i]>Alph[i]){
res = 0;break;
}
}
return res;
}
int countCharacters(char ** words, int wordsSize, char * chars){
if(strlen(chars)==0) return 0;
if(wordsSize==0) return 0;
int ans;
ans = 0;
for(int i=0;i<strlen(chars);i++){
Alph[chars[i]-'a']++;
}
for(int i=0;i<wordsSize;i++){
if(isJizhu(words, i) == 1){
ans = ans + strlen(words[i]);
}
}
return ans;
}
將Alph改成局部變量就OK了
//正解
int isJizhu(char ** words, int index, int * Alph){
int res = 1;
int beta[26] = {0};
for(int i=0;i<26;i++){
beta[i] = 0;
}
for(int i=0;i<strlen(words[index]);i++){
beta[words[index][i] - 'a']++;
}
for(int i=0;i<26;i++){
if(beta[i]>Alph[i]){
res = 0;break;
}
}
return res;
}
int countCharacters(char ** words, int wordsSize, char * chars){
if(strlen(chars)==0) return 0;
if(wordsSize==0) return 0;
int Alph[26];
for(int i=0;i<26;i++){
Alph[i] = 0;
}
int ans;
ans = 0;
for(int i=0;i<strlen(chars);i++){
Alph[chars[i]-'a']++;
}
for(int i=0;i<wordsSize;i++){
if(isJizhu(words, i, Alph) == 1){
ans = ans + strlen(words[i]);
}
}
return ans;
}
深刻的反思
全局變量這種生命週期自己說了不算的變量,儘量不要爲了少寫一點初始化代碼而偷懶用它了。
這個問題之所以會在leetcode中出現,而在ACM中很少見,是因爲,ACM是ACMer自己來處理輸入輸出的,所以整個測試過程是ACMer自己把握的,因此ACMer知道,自己定義的全局變量要不要重新賦值,比如這個題,如果讓我寫輸入輸出的code,我就會注意重新對Alph賦值的。
leetcode去掉了初始化的煩惱,好壞參半。
教訓
刷leetcode不用全局變量!!!