KMP字符串
给定一个字符串 S,以及一个模式串 P,所有字符串中只包含大小写英文字母以及阿拉伯数字。
模式串 P在字符串 S 中多次作为子串出现。
求出模式串 P 在字符串 S 中所有出现的位置的起始下标。
输入格式
第一行输入整数 N,表示字符串 P 的长度。
第二行输入字符串 P。
第三行输入整数 M,表示字符串 S 的长度。
第四行输入字符串 S。
输出格式
共一行,输出所有出现位置的起始下标(下标从 00 开始计数),整数之间用空格隔开。
数据范围
1≤N≤1E5
1≤M≤1E6
输入样例:
输出样例:
个人代码
| 12
 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
 
 | #include<bits/stdc++.h>using namespace std;
 string tool;
 string aim;
 vector<int>pre;
 void buildNext() {
 int i = 0;
 
 pre.push_back(0);
 
 for(int j=1;j<tool.size();j++){
 while(i !=0 && tool[i] != tool[j]){
 i = pre[i-1];
 }
 if(tool[i] == tool[j]) {
 i++;
 }
 pre.push_back(i);
 }
 }
 int main() {
 int n,m;
 cin>>n;cin>>tool;
 cin>>m;cin>>aim;
 buildNext();
 vector<int> res;
 
 int index = 0;
 for(int i=0;i<m;i++){
 while (index != 0 &&tool[index] != aim[i]) {
 index = pre[index - 1];
 }
 if (tool[index] == aim[i]) {
 index++;
 if (index == n) {
 res.push_back(i - index + 1);
 
 index = pre[index - 1];
 
 
 
 
 }
 }
 }
 for(int i=0;i<res.size();i++){
 printf("%d ",res[i]);
 }
 
 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 | 
板子
| 12
 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
 
 | #include <iostream>
 using namespace std;
 
 const int N = 100010, M = 1000010;
 
 int n, m;
 int ne[N];
 char s[M], p[N];
 
 int main()
 {
 cin >> n >> p + 1 >> m >> s + 1;
 
 for (int i = 2, j = 0; i <= n; i ++ )
 {
 while (j && p[i] != p[j + 1]) j = ne[j];
 if (p[i] == p[j + 1]) j ++ ;
 ne[i] = j;
 }
 
 for (int i = 1, j = 0; i <= m; i ++ )
 {
 while (j && s[i] != p[j + 1]) j = ne[j];
 if (s[i] == p[j + 1]) j ++ ;
 if (j == n)
 {
 printf("%d ", i - n);
 j = ne[j];
 }
 }
 
 return 0;
 }
 
 
 
 
 
 
 |