题目
思路
BF算法找到匹配的子串
注意点① 替换子串需要把后续部分移动,右移和左移不一样
注意点② 替换完字串后,i要+=替换字串长度,s的长度也要更新
代码
#include<stdio.h>
#include<iostream>
using namespace std;
#define N 80
#include<string.h>
void replace(char s[], char x[], char y[])
{ //TODO: your function definition
//BF法
int sl = strlen(s);
int xl = strlen(x);
int yl = strlen(y);
for(int i = 0; i < sl; i++)
{
int flag = 0;
for(int j = 0; j < xl; j++)
{
if(s[i + j] != x[j])
break;
if(j == xl - 1)
flag = 1;
}
if(flag)
{
//cout << i <<endl;
int move = yl - xl;
if(move >= 0)
{
for(int j = sl - 1; j >= i + xl; j--)
{
s[j + move] = s[j];
}
}
else
{
for(int j = i + xl; j < sl; j++)
{
s[j + move] = s[j];
}
}
for(int j = 0; j < yl; j++)
s[i + j] = y[j];
s[sl + move] = 0;
sl = strlen(s);
i += yl - 1;
}
}
}
int main() {
char s[3 * N + 1], x[N + 1], y[N + 1];
scanf("%s%s%s", s, x, y);
replace(s, x, y);
printf("%s\n", s);
return 0;
}