平时刷题之word chain

问:
一个字符串插入或者减少一个字符变成新字符,或者是更改某一个字符,变成新字符,则称新字符串跟原来字符串能够成为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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值