Implement strStr()--字符串匹配_kmp_bkdHash
来源:互联网 发布:中国消防网站的域名 编辑:程序博客网 时间:2024/06/03 17:31
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
两种方法:
1)bkdHash
2)kmp
代码分别如下:
//bkdHash
int strStr(string haystack, string needle) { typedef unsigned long long ull; int size1 = haystack.size(), size2 = needle.size(); if(size1<size2) return -1; ull* Hash = new ull[size1+1]; ull nbase = 1; //因为size2是知道的,不用计算nbase[i] int i, base = 31; //并给haystack建立bkdHash Hash[0] = 0; for(i = 1; i <= size1; ++i) Hash[i] = Hash[i-1]*base + haystack[i-1] - 'a' + 1; //计算needle的hash值, 计算nbase, ull h = 0; for(i = 0; i < size2; ++i){ nbase = nbase*base; h = h*base + needle[i] - 'a' + 1; } for(i = size2; i <= size1; ++i) if(Hash[i] - Hash[i-size2]*nbase==h) return i-size2; delete [] Hash; return -1; }
//kmp int strStr(string haystack, string needle) { int size1 = haystack.size(), size2 = needle.size(); if(size1<size2) return -1; if(needle=="") return 0; int *next = getNext(needle); int i, j = 0; for(i = 0; i < size1; ++i){ if(j==-1||haystack[i]==needle[j]){ if(++j==size2) return i-j+1; } else{ j = next[j]; i--; } } delete [] next; return -1; } //next数组 int* getNext(string& needle){ int i, j, size = needle.size(); int *next = new int[size]; memset(next, 0, sizeof(int)*size); next[0] = -1; for(i = 1; i < size; ++i){ j = i-1; while(next[j]>=0){ if(needle[i-1]==needle[next[j]]){ next[i] = next[j] + 1; break; } else j = next[j]; } } return next; }
1 0
- Implement strStr()--字符串匹配_kmp_bkdHash
- 【字符串匹配】Implement strStr()
- 字符串匹配Implement strStr()
- 【KMP&字符串匹配】Implement strStr()
- [LeetCode]Implement strStr() 字符串匹配
- leetcode 字符串匹配Implement strStr()
- (LeetCode)Implement strStr() --- 匹配字符串
- Implement strStr() 字符串匹配(KMP)
- 28. Implement strStr()(String字符串匹配)
- LeetCode-28-Implement strStr()(字符串匹配)
- Implement strStr() (匹配字符串问题,哈希解法) 【leetcode】
- [LeetCode-28] Implement strStr(KMP 字符串匹配)
- 28.LeetCode Implement strStr()(meidum)[字符串 子串匹配]
- LeetCode: Implement strStr()(字符串匹配:Sunday算法)
- 28-Implement strStr()(匹配字符串问题KMP算法)
- leetcode---implement-strstr---字符串
- 【字符串匹配】KMP(implement strStr()), 正则匹配(Wildcard Matching),2-dim 动规(regular expression)
- leetcode_28. Implement strStr() 字符串模式匹配,返回匹配的首字符位置
- 浏览器查看pdf插件pdfobject
- iOS安全系列之一:HTTPS
- 入门级:GitHub和Git超超超详细使用教程!
- 第十五周--B-树的操作
- python 排序
- Implement strStr()--字符串匹配_kmp_bkdHash
- Yii2 Formatter 格式化使用
- Thirteenth records of career
- Cartographer+北阳雷达实现
- java基本加密方式
- Kafka重启出错:Corrupt index found,
- 51nod 1400 序列分解【Dfs+剪枝】好题~
- IOS应用内购买(InApp Purchase)总结
- 高并发下出现的一个问题