hdoj 2087 如何制作剪花布条?

2026-05-29 14:053阅读0评论SEO问题
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计334个文字,预计阅读时间需要2分钟。

hdoj 2087 如何制作剪花布条?

题目链接:剪花布条题目大意:给你一个模式串和一个原串,问能从原串中剪出多少个模式串。题目思路:KMP算法,只需要在i的遍历过程中,当出现不匹配时,将模式串的前缀后缀进行比较,如果相等,则将j指向j的前一个位置,否则将j指向0。


题目链接:​​剪花布条​​

题目大意:给你一个模式串和原串,问能从原串中剪出多少个模式串来

题目思路:KMP,只不过在i的遍历时需要将他提到匹配后j的后一个字符去,这样就不会出现被剪过的字符再次匹配的情况

#include <bits/stdc++.h>

using namespace std;
const int maxn = 1e6+10;

char str[maxn],mo[maxn];
int Next[maxn];

void getNext(){
int i = 0,j = -1,len = strlen(mo);
while(i < len){
if(j == -1||mo[i] == mo[j]) Next[++i] = ++j;
else j = Next[j];
}
}

int kmp(){
int i = 0,j = 0,l1 = strlen(str),l2 = strlen(mo);
int ans = 0;
while(i < l1){
if(j == -1||mo[j] == str[i])
i++,j++;
else j = Next[j];
if(j == l2){
ans++;
i = i+j-1;
}
}
return ans;
}

int main(){
while(~scanf("%s",str)){
if(str[0] == '#') break;
scanf("%s",mo);
Next[0] = -1;
getNext();
printf("%d\n",kmp());
}
return 0;
}


hdoj 2087 如何制作剪花布条?

本文共计334个文字,预计阅读时间需要2分钟。

hdoj 2087 如何制作剪花布条?

题目链接:剪花布条题目大意:给你一个模式串和一个原串,问能从原串中剪出多少个模式串。题目思路:KMP算法,只需要在i的遍历过程中,当出现不匹配时,将模式串的前缀后缀进行比较,如果相等,则将j指向j的前一个位置,否则将j指向0。


题目链接:​​剪花布条​​

题目大意:给你一个模式串和原串,问能从原串中剪出多少个模式串来

题目思路:KMP,只不过在i的遍历时需要将他提到匹配后j的后一个字符去,这样就不会出现被剪过的字符再次匹配的情况

#include <bits/stdc++.h>

using namespace std;
const int maxn = 1e6+10;

char str[maxn],mo[maxn];
int Next[maxn];

void getNext(){
int i = 0,j = -1,len = strlen(mo);
while(i < len){
if(j == -1||mo[i] == mo[j]) Next[++i] = ++j;
else j = Next[j];
}
}

int kmp(){
int i = 0,j = 0,l1 = strlen(str),l2 = strlen(mo);
int ans = 0;
while(i < l1){
if(j == -1||mo[j] == str[i])
i++,j++;
else j = Next[j];
if(j == l2){
ans++;
i = i+j-1;
}
}
return ans;
}

int main(){
while(~scanf("%s",str)){
if(str[0] == '#') break;
scanf("%s",mo);
Next[0] = -1;
getNext();
printf("%d\n",kmp());
}
return 0;
}


hdoj 2087 如何制作剪花布条?