【算法】字符串匹配问题
2017-02-14 03:59
302 查看
28. Implement strStr()
KMP算法
KMP算法我觉得KMP算法的Next数组详解这篇文章讲的还是非常的透彻的。vector<int> next; void getnext(const string &needle){ next[0] = -1; int i = 0,k = -1; //还要注意这个地方,不要漏了后面那个-1 while(i<needle.size()-1){ if(k == -1 || needle[i] == needle[k]) next[++i] = ++k; else k = next[k]; } } int kmp(const string& haystack,const string& needle){ int i = 0,j = 0; //注意一下这个地方的神坑点就行,size()函数返回的是unsigned类型,做类型比较的话,当j=-1时,会将j变为unsigned的类型,然后判断出j>needle.size(),从而不进入判断。 while(i<haystack.size()&&(j==-1||j<needle.size())){ if(j == -1 || haystack[i] == needle[j]){ i++; j++; }else{ j = next[j]; } } if(j == needle.size()) return i-j; return -1; } int strStr(string haystack, string needle) { if(needle.size() == 0) return 0; next = vector<int> (needle.size(),0); getnext(needle); return kmp(haystack,needle); }
相关文章推荐
- 字符串匹配之通配符问题------一串首尾相连的珠子(m个),有N种颜色(N《=10),设计一个算法,取出其中一段,要求包含所有N中颜色,并使长度最短。
- 常见算法及问题场景——字符串匹配
- 子字符串substring 问题 - KMP 字符串匹配算法备忘录
- 算法实现字符串匹配问题:从三个字符串中找出共有的最长部分。
- 第32章:字符串匹配问题: 朴素算法,Rabin-Karp算法
- 字符串匹配之通配符问题------一串首尾相连的珠子(m个),有N种颜色(N《=10),设计一个算法,取出其中一段,要求包含所有N中颜色,并使长度最短。
- 玩转经典算法之字符串匹配(一) 问题引入和朴素的匹配算法
- Boyer-Moore(BM)算法,文本查找,字符串匹配问题
- 最长字符串匹配算法(KMP算法)
- 程序员面试题精选(52):字符串匹配实现(回溯与不回溯算法)
- 几种字符串匹配算法性能简单实验对比
- BM字符串匹配算法
- 字符串匹配算法
- kmp字符串匹配算法
- 3月24日 想到了一个字符串匹配的新算法 程序 时间复杂度自己不会算
- 字符串匹配算法:KMP算法与BM算法比较
- 字符串匹配算法:KMP学习心得
- 字符串匹配之朴素算法和通配符扩展
- 最长字符串匹配算法(KMP算法)
- 字符串匹配算法研究(二)