练KMP我认为没什么技巧,背代码就完事了。我的口诀:(仅限于自己理解)
(1)、先回溯主串后回溯子串,回溯哪个哪个为负一;
(2)、推nextTable时拿子串对应的下标开刀。
PS:这题把nextTable数组换成next数组居然有歧义,这辣鸡编译器居然还会把next数组设成关键字,第一次碰到这种错害得我检查了一个小时,真是绝了。
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <climits>
using namespace std;
const int MAXN = 1000005;
const int INF = INT_MAX;
int nextTable[MAXN];
void getNext(string &text, string &pattern){
int n = text.size();
int m = pattern.size();
int i, j;
j = 0;
nextTable[j] = -1;
i = nextTable[j];
while(j < m){
if(i == -1 || pattern[i] == pattern[j]){
i++;
j++;
nextTable[j] = i;
}
else{
i = nextTable[i];
}
}
}
int KMP(string &text, string &pattern){
getNext(text, pattern);
int n = text.size();
int m = pattern.size();
int i, j, ans;
i = j = ans = 0;
while(i < n && j < m){
if(j == -1 || text[i] == pattern[j]){
i++;
j++;
}
else{
j = nextTable[j];
}
if(j == m){
ans++;
j = nextTable[j];
}
}
return ans;
}
int main(){
// freopen("in.txt", "r", stdin);
string text, pattern;
while(cin >> text >> pattern){
printf("%d\n", KMP(text, pattern));
}
return 0;
}
连续两个遇到牛客的辣鸡题,上一个是编译器的问题,这个是题目没说清楚。明明题目中说了"并且可以有一个用中括号表示的模式匹配",是只有一个括号,结果后来卡在688那个例子傻了半天,无奈看评论发现不只有一个括号。nnd,只能重写一遍匹配了。有点不舒服,A了是运气。
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <cctype>
#include <climits>
using namespace std;
const int MAXN = 1005;
const int INF = INT_MAX;
int main(){
// freopen("in.txt", "r", stdin);
int n;
string pattern;
string table[MAXN], tabletmp[MAXN];
while(~scanf("%d", &n)){
//if(n == 0) break;
for(int i = 0; i < n; i++){
cin >> table[i];
}
cin >> pattern;
//初始化
for(int i = 0; i < n; i++){
tabletmp[i] = table[i];
for(int j = 0; j < tabletmp[i].size(); j++){
if(isupper(tabletmp[i][j])) tabletmp[i][j] = tolower(tabletmp[i][j]);
}
}
for(int i = 0; i < pattern.size(); i++){
if(isupper(pattern[i])) pattern[i] = tolower(pattern[i]);
}
//模式串匹配
for(int i = 0; i < n; i++){
bool flag1 = true;
int num = 0;
for(int j = 0; j < tabletmp[i].size(); j++){
if(pattern[num] == '['){
if(pattern[num+1] == ']') continue;
bool flag2 = false;//初始为匹配不到
num++;
while(pattern[num] != ']'){
if(pattern[num] == tabletmp[i][j]) flag2 = true;//匹配到
num++;
}
if(!flag2){
flag1 = false;
break;
}
num++;
continue;
}
if(pattern[num] != tabletmp[i][j]){
flag1 = false;
break;
}
num++;
}
if(num != pattern.size()) flag1 = false;
if(flag1) cout << i+1 << " " << table[i] << endl;
}
}
return 0;
}
来源:CSDN
作者:Flynn_curry
链接:https://blog.csdn.net/Flynn_curry/article/details/104702601