閱讀以下說明和C程序,填補代碼中的空缺(1)~(5),將解答填入答題紙的對應欄內。
【說明】
函數(shù)areAnagrams(char *fstword, char *sndword)的功能是判斷fstword和sndword中的單詞(不區(qū)分大小寫)是否互為變位詞,若是則返回1,否則返回0。所謂變位詞是指兩個單詞是由相同字母的不同排列得到的。例如,“triangle”與“integral”互為變位詞,而“dumbest”與“stumble”不是。
函數(shù)areAnagrams的處理思路是檢測兩個單詞是否包含相同的字母且每個字母出現(xiàn)的次數(shù)也相同。過程是先計算第一個單詞(即fstword中的單詞)中各字母的出現(xiàn)次數(shù)并記錄在數(shù)組counter中,然后掃描第二個單詞(即sndword中的單詞)的各字母,若在第二個單詞中遇到與第一個單詞相同的字母,就將相應的計數(shù)變量值減1,若在第二個單詞中發(fā)現(xiàn)第一個單詞中不存在的字母,則可斷定這兩個單詞不構成變位詞。最后掃描用于計數(shù)的數(shù)組counter各元素,若兩個單詞互為變位詞,則counter的所有元素值都為0。
函數(shù)areAnagrams中用到的部分標準庫函數(shù)如下表所述。
【C函數(shù)】
int areAnagrams (char *fstword, char *sndword)
{
int index;
int counter [26]={0}; /* counter[i]為英文字母表第i個字母出現(xiàn)的次數(shù),
'A'或'a'為第0個,'B'或'b'為第1個,依此類推 */
if ( (1) ) /* 兩個單詞相同時不互為變位詞 */
return 0;
while(*fstword) { /* 計算第一個單詞中各字母出現(xiàn)的次數(shù) */
if (isalpha (*fstword)) {
if (isupper (*fstword))
counter [*fstword -'A']++;
else
counter [*fstword -'a']++;
(2) ; /* 下一個字符 */
}
}
while (*sndword) {
if (isalpha (*sndword)) {
index= isupper (*sndword) ? *sndword -'A': *sndword -'a';
if (counter [index] )
counter [index] --;
else
(3) ;
}
(4) ; /* 下一個字符 */
}
for (index = 0; index<26; index++)
if ( (5) )
return 0;
return 1;
}