比KMP算法更简洁,更高效的sunday算法
2017-12-03 21:15
239 查看
KMP算法中next数组计算比较难懂,sunday算法更高效,但是网络中各个版本都有bug,自己调试的无错误的权当作笔记:
//sunday算法/*,Sunday算法其实思想跟BM算法很相似,只不过Sunday算法是从前往后匹配,在匹配失败时关注的是文本串中参加匹配的最末位字符的下一位字符。如果该字符没有在匹配串中出现则直接跳过,即移动步长= 匹配串长度+ 1;否则,同BM算法一样其移动步长=匹配串中最右端的该字符到末尾的距离+1。*/#include <iostream>#include <string>using namespace std;class Solution {public:int strStr(string haystack, string needle){int len_s = haystack.size();int len_d = needle.size();int next[26] = {0};for(int j = 0; j < 26; ++j)next[j] = len_d + 1;for(int j = 0; j < len_d; ++j)next[needle[j] - 'a'] = len_d - j;//例如:needle = "abcedfb"//next = {7 1 5 4 3 2 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8}int pos = 0;while(pos < (len_s - len_d + 1)){int i = pos;int j;for(j = 0; j < len_d; ++j,++i){if(haystack[i] != needle[j]){if(pos + len_d > len_s - 1)return -1;pos += next[haystack[pos + len_d] - 'a'];break;}}if(j == len_d)return pos;}return -1;}};int main(int argc, char **argv){string haystack = "aaaaa";string needle = "bba";cout<<Solution().strStr(haystack, needle)<<endl;return 0;}注:本版本只能比较含有小写字母的字符串,若含有其它非小写字母(例如空格,大写字母,需要更改)
相关文章推荐
- SmartJNI —— 更简洁更高效的JNI接口封装
- 较为简洁明了的KMP算法解释
- Sunday算法和KMP算法
- 更高效、简洁、方便的协议框架
- 字符串匹配(find函数,KMP算法,Sunday算法)
- ESL:更简洁、更高效的标准加载器
- hzjs颠覆jquery,按照中国人思维开发的最简洁的JQUERY替代品更简洁更高效
- KMP算法详解:简洁易懂的KMP算法,下边有许多
- hzjs颠覆jquery,按照中国人思维开发的最简洁的JQUERY替代品更简洁更高效
- 字符串匹配算法——Sunday算法和KMP算法(java版本)
- Dropbox网站全新改版:清新、简洁、更高效
- 使用 sphinx 制作简洁而又美观的文档
- 看懂php单例模式-清晰简洁的回答
- 老师私房菜之如何学得比别人更高效
- Sunday算法模板
- 字符串匹配的KMP算法
- ssm+redis 如何更简洁的利用自定义注解+AOP实现redis缓存
- KMP算法
- KMP hihoCoder1015 KMP算法
- 写了个android简洁的日志打印工具类。