设 计如 下 算 法

;设计如下算法: char* StrRelace(char T[], charP[], char S[]),将T中第- -次出现的与P相等的子串替换为S(串S和P的长度不一定相等),并分析时间复杂度。

#include"stdio.h"
#define MAXNUNM 200
int n=0;
void replace(char chString[],char chOldWord[],char chNewWord[]){

    int i,nStartPos=0,nLen1=0,nLen2=0,nLen3=0,nFound;/*计算旧词和新词的长度*/
    while(chOldWord[nLen2++]!='\0');
    nLen2--;
    while(chNewWord[nLen3++]!='\0');
    nLen3--;
    /*chString 中可能有多个旧词,均要替换为新词;利用循环向前拨动查找位置,逐次进行比较和替换*/
    while(chString[nStartPos]!='\0'){

        nFound=1;
        for(i=0;i<nLen2;i++)
        if(chString[nStartPos+i]!=chOldWord[i]){
            nFound=0; break;
        }

        if(nFound==1){
             n++;
             while(chString[nLen1++]!='\0');
             nLen1--;
             if(nLen3-nLen2>=0){
                for(i=nLen1-1;i>=nStartPos;i--)
                    chString[i+nLen3-nLen2]=chString[i];
             }

            else{
                for(i=nStartPos+nLen2;i<nLen1;i++)
                    chString[i+nLen3-nLen2]=chString[i];
            }

            chString[nLen1+nLen3-nLen2]='\0';
            for(i=0;i<nLen3;i++)
                chString[nStartPos+i]=chNewWord[i];
            nStartPos+=nLen3;


        }
        else{
            nStartPos++;
        }
    }
}

int main(){
    char chStr[100],chOld[100],chNew[100];
    scanf("%s",&chStr);
	scanf("%s",&chOld);
	scanf("%s",&chNew);

    replace(chStr,chOld,chNew);/*输出结果*/
    printf("%s",chStr);
    printf("\n");
    //printf("%d",n);
	return 0;
}

 

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632