数据结构算法——1036. 字符串替换

题目

在这里插入图片描述

思路

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;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值