zoukankan      html  css  js  c++  java
  • 牛客算法周周练18B

    在这里插入图片描述在这里插入图片描述

    题目大意:

    给出三个串 A B C,你的任务是从A中找到所有子串和B相等的串并替换为C串,输出替换后的字符串。

    解题思路:

    kmp模板题,套用kmp的板子,每次找B串,然后用sting.replace()换掉即可,如果找不到则退出循环。

    Code:

    /*kmp*/
    #pragma GCC optimize(2)
    #include <cstdio>
    #include <iostream>
    #include <algorithm>
    #include <cmath>
    #include <vector>
    #include <queue>
    #include <stack>
    #include <map>
    #include <set>
    #include <cstring>
    using namespace std;
    typedef long long ll;
    typedef pair<int, int> pii;
    const int N = 1e6 + 50;
    const int inf = 0x3f3f3f3f;
    int nextval[N];
    string s, a, b;
    void get_next()//求next数组
    {
    	int j = 0, k=-1;
    	nextval[0] = -1;
        int slen = a.size();
    	while (j < slen)
    	{
    		if (k == -1 || a[j] == a[k])
    		{
    			j++; k++;
    			nextval[j] = k;
    		}
    		else k = nextval[k];//类似递归的去找公共前后缀
    	}
    }
    int kmp()//模板
    {
       int i = 0, j=0;
       int slen = s.size(), plen = a.size();
       while (i < slen && j < plen)
       {
    		if(j == -1 || s[i] == a[j])
    		{
    			i++;
    			j++;
    		}
    		else j = nextval[j];
       }
       if(j == plen)
           return i - j; 
        return -1; 
    }
    int main()
    {
    	ios::sync_with_stdio(false);
    	cin >> s >> a >> b;
    	int len = a.size();
    	get_next();
    	while (true)
    	{
    		int pos = kmp();//每次找a出现的第一个位置
    		if (pos == -1)  break;
    		s.replace(pos, len, b);
    	}
    	cout << s << endl;
    	return 0;
    }
    

    这道题还有STL做法,就是find和replace交替使用也可以AC。代码如下:

    /*STL做法*/
    #pragma GCC optimize(2)
    #include <cstdio>
    #include <iostream>
    #include <algorithm>
    #include <cmath>
    #include <vector>
    #include <queue>
    #include <stack>
    #include <map>
    #include <set>
    #include <cstring>
    using namespace std;
    typedef long long ll;
    typedef pair<int, int> pii;
    const int N = 250;
    const int inf = 0x3f3f3f3f;
    int main()
    {
        ios::sync_with_stdio(false);
        string s, a, b;
        cin >> s >> a >> b;
        int len = a.size();
        while (true)
        {
            int pos = s.find(a);
            if (pos == -1)  break;
            s.replace(pos, len, b);
        }
        cout << s << endl;
        return 0;
    }
    
  • 相关阅读:
    7. 输油管道问题
    6. 循环赛日程表
    4.JSP内置对象
    3.JSP
    2.CSS
    1.HTML
    5. 逆序对数
    [转]Android View.onMeasure方法的理解
    [转]android:clipToPadding和android:clipChildren
    [转]倍数提高工作效率的 Android Studio 奇技
  • 原文地址:https://www.cnblogs.com/Hayasaka/p/14294162.html
Copyright © 2011-2022 走看看