字符串匹配--KMP算法
2017-09-27 19:49
302 查看
Problem Description
给定两个字符串string1和string2,判断string2是否为string1的子串。
Input
输入包含多组数据,每组测试数据包含两行,第一行代表string1,第二行代表string2,string1和string2中保证不出现空格。(string1和string2大小不超过100字符)
Output
对于每组输入数据,若string2是string1的子串,则输出”YES”,否则输出”NO”。
Example Input
abc
a
123456
45
abc
ddd
Example Output
YES
YES
NO
看了一天的KMP,对KMP算法可以说是相当无语了。。。
数据结构课本上的伪代码也是让人抓狂。。。
next数组干脆改名叫做torture数组吧!
好不容易A了一道KMP题,抓紧记录下来。。。(暂时仍对KMP理解不深刻,还是等到脑子清醒再重新梳理一遍吧)
给定两个字符串string1和string2,判断string2是否为string1的子串。
Input
输入包含多组数据,每组测试数据包含两行,第一行代表string1,第二行代表string2,string1和string2中保证不出现空格。(string1和string2大小不超过100字符)
Output
对于每组输入数据,若string2是string1的子串,则输出”YES”,否则输出”NO”。
Example Input
abc
a
123456
45
abc
ddd
Example Output
YES
YES
NO
看了一天的KMP,对KMP算法可以说是相当无语了。。。
数据结构课本上的伪代码也是让人抓狂。。。
next数组干脆改名叫做torture数组吧!
好不容易A了一道KMP题,抓紧记录下来。。。(暂时仍对KMP理解不深刻,还是等到脑子清醒再重新梳理一遍吧)
#include<iostream> #include<string> using namespace std; const int M=1e6+10; void Getnext(string t,int next[]) { int i=0,j=-1; next[0]=-1; int len=t.size(); while(i<len) { if(j==-1||t[i]==t[j]) { next[++i]=++j; if(t[i]==t[j]) next[i]=next[j]; } else j=next[j]; } } bool index_KMP(string s,string t,int next[]) { int i=0,j=0; int len1=s.size(),len2=t.size(); while(i<len1&&j<len2) { if(j==-1||s[i]==t[j]) { i++;j++; } else { j=next[j]; } } if(j>=len2) return true; else return false; } int main() { string s,t; int i; while(cin>>s) { int next[M+50]= {0}; cin>>t; Getnext(t,next); int flag=index_KMP(s,t,next); if(flag==0) cout<<"NO"<<endl; else cout<<"YES"<<endl; } }
相关文章推荐
- KMP算法---字符串匹配
- [转载]字符串匹配的KMP算法
- 字符串匹配的KMP算法 作者: 阮一峰 http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_al
- 字符串匹配的KMP算法(转)
- 字符串匹配的KMP算法
- 字符串匹配的KMP算法-16张图片看明白
- 字符串匹配的KMP算法
- 每天写一点代码----字符串匹配1(KMP算法)
- 数据结构之 字符串---字符串匹配(kmp算法)
- 字符串匹配之KMP算法
- 字符串匹配之KMP算法详解
- 字符串匹配算法——KMP算法
- 字符串匹配的KMP算法(转)
- 字符串匹配的KMP算法
- 字符串匹配的KMP算法
- 字符串匹配的KMP算法
- 字符串匹配之KMP算法初探
- 字符串匹配的KMP算法详解
- 字符串匹配—KMP算法
- C++实现字符串匹配的KMP算法