问:
一个字符串插入或者减少一个字符变成新字符,或者是更改某一个字符,变成新字符,则称新字符串跟原来字符串能够成为wordchain。
要求写这么一个函数来实现这个功能
写的原理就是分几类,差距为2字符直接排除,然后相同字符长度用规则去匹配,同样不同字符长度也是如此。
函数如下:
int CompareTwoWords(char word1[], char word2[]){
int len1 = strlen(word1);
int len2 = strlen(word2);
if (abs((int)(len1-len2)) > 1){ //if more than two,prove false
return 0;
}
//if equal
if (len1 == len2){
int pos = 0;
int i;
for (i = 0; i < len1; i++){
if (word1[i] != word2[i]){
pos = i;
int j;
for (j = pos + 1; j < len1; j++){
if (word1[j] != word2[j]){
return 0;
}
}
break;
}
}
}
//if left for one char distance,for code length,deal with something
else{
char str_large[20], str_small[20];
if (len1 > len2){
strcpy(str_large, word1);
strcpy(str_small, word2);
}
else if (len1 < len2){
strcpy(str_large, word2);
strcpy(str_small, word1);
}
int i;
for (i = 0; i < strlen(str_small); i++){
if (str_small[i] != str_large[i]){
int pos = i;
int j;
for (j = pos; j < strlen(str_small); j++){
if (str_small[j] != str_large[j + 1]){
return 0;
}
}
break;
}
}
}
return 1;
}