题目描述
给出主串、模式串、替换串,用KMP算法找出模式串在主串的位置,然后用替换串的字符替换掉模式串
本题只考虑一处替换的情况,如果你想做的完美一些,能够实现多处替换那
可能需要考虑模式串和替换串长度不一致的情况
输入
第一个输入t,表示有t个实例
第二行输入第1个实例的主串,第三行输入第1个实例的模式串,第四行输入第1个实例的替换串
以此类推
输出
第一行输出第1个实例的主串
第二行输出第1个实例的主串替换后结果,如果没有发生替换就输出主串原来的内容。
以此类推
样例输入
3 aabbccdd bb ff aaabbbccc ddd eee abcdef abc ccccc
样例输出
aabbccdd aaffccdd aaabbbccc aaabbbccc abcdef cccccdef
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68#include <iostream> #include <string> using namespace std; int *get_next(string s) { int *n=new int[s.length()]; n[0]=-1; int i,j; i=0; j=-1; while(i<s.length()-1) { if(j==-1 || s[i]==s[j]) { i++; j++; n[i]=j; } else j=n[j]; } return n; } int KMP(string s,string key) { int *n=get_next(key); int i=0,j=0; int s_l=s.length(),j_l=key.length(); while(i<s_l && j<j_l) { if(j==-1 || s[i]==key[j]) { i++; j++; } else { j=n[j]; } } if(j==key.length()) return i-key.length()+1; else return 0; } int main() { string s,key,rekey; int *n; int t,temp; cin>>t; while(t--) { cin>>s>>key>>rekey; cout<<s<<endl; temp=KMP(s,key); if(temp==0) cout<<s<<endl; else { s.erase(temp-1,key.size()); s.insert(temp-1,rekey); cout<<s<<endl; } } return 0; }
最后
以上就是潇洒汽车最近收集整理的关于串替换的全部内容,更多相关串替换内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复