本文共 2453 字,大约阅读时间需要 8 分钟。
这两题都是统计一个字符串中另一个字符串的数量,只不过一题允许重叠,另一题不能重叠。两题在代码上最大的区别在于输入格式的处理,其实也就是找到了一个文本串和模式串匹配的子串之后,是不是从模式串开头重新找的区别。
第一题的AC代码如下:
#include#include #include using namespace std;#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);#define read(x) (x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = (x << 1) + (x << 3) + (ch ^ 48); ch = getchar(); } return x * f)void get_nxt() { ll lenb = strlen(b); int j = 0, k = -1; nxt[0] = -1; while (j < lenb) { if (k == -1 || b[j] == b[k]) nxt[++j] = ++k; else k = nxt[k]; }}ll KMP() { ll lenb = strlen(b), lena = strlen(a), res = 0; get_nxt(); ll i = 0, j = 0; while (i < lena) { if (j == -1 || a[i] == b[j]) i++, j++; else j = nxt[j]; if (j == lenb) { res++; // j = nxt[j]; j = 0; } } return res;}int main() { IOS; ll n; while (cin >> a) { if (a[0] == '#') break; cin >> b; cout << KMP() << endl; } return 0;}
第二题的AC代码如下:
#include#include #include using namespace std;#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);#define read(x) (x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = (x << 1) + (x << 3) + (ch ^ 48); ch = getchar(); } return x * f)void get_nxt() { ll lenb = strlen(b); int j = 0, k = -1; nxt[0] = -1; while (j < lenb) { if (k == -1 || b[j] == b[k]) nxt[++j] = ++k; else k = nxt[k]; }}ll KMP() { ll lenb = strlen(b), lena = strlen(a), res = 0; get_nxt(); ll i = 0, j = 0; while (i < lena) { if (j == -1 || a[i] == b[j]) i++, j++; else j = nxt[j]; if (j == lenb) { res++; j = nxt[j]; j = 0; } } return res;}int main() { IOS; ll n; cin >> n; while (n--) { if (a[0] == '#') break; cin >> b >> a; cout << KMP() << endl; } return 0;}
两题在KMP算法的实现上,最大的区别是处理匹配完成之后的逻辑。第一题在匹配完成后(即j == lenb)会将j重置为0,允许重叠匹配;而第二题则不会重置j,而是继续在当前位置寻找下一个匹配,导致不能重叠。
转载地址:http://igod.baihongyu.com/