Implement strStr()
来源:互联网 发布:知美术馆路线 编辑:程序博客网 时间:2024/06/05 11:34
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
题意:
实现strstr(). 返回needle(关键字)在haystack(字符串)中第一次出现的位置,如果needle不在haystack中,则返回-1。
注:strstr()是c++中的一个函数
采用kmp算法(这个后续再来实现)
class Solution {public: int strStr(string haystack, string needle) { return KmpSearch(haystack,needle); } int KmpSearch(string s, string p) { int i = 0; int j = 0; int sLen = s.size(); int pLen = p.size(); int next[pLen]; GetNext(p,next); while (i < sLen && j < pLen) { //①如果j = -1,或者当前字符匹配成功(即S[i] == P[j]),都令i++,j++ if ( j == -1 ||s[i] == p[j]) { i++; j++; } else { //②如果j != -1,且当前字符匹配失败(即S[i] != P[j]),则令 i 不变,j = next[j] //next[j]即为j所对应的next值 j = next[j]; //第一次匹配时,j=next[j]=next[0]=-1,所以会出现j=-1的情况,这种情况,要移动。只有-1,表示不匹配才移动。 //0这种情况下,还是要将j移动到0位置与i进行比较。如果匹配失败,则将j置为-1。 } } if (j == pLen) return i - j; else return -1; } void GetNext(string p,int next[]) { int pLen =p.size(); next[0] = -1; int k = -1; int j = 0; while (j < pLen - 1) { //p[k]表示前缀,p[j]表示后缀 ,如果p[j] == p[k],表示j位置上的和k位置上的相等。否则不等。 if (k == -1 || p[j] == p[k]) { ++k; ++j; if(p[j]!=p[k]) { next[j] = k; } else next[j]=next[k];//让k=next[k]继续循环下去 } else { k = next[k]; //递归找到那个k位置。直到p[j]==p[k],或者k==-1。 } } } };
0 0
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- 测试的核心技术
- LeetCode:Palindrome Linked List
- 计算机视觉相关会议期刊
- 异常的实例
- 机器学习 libsvm交叉验证与网格搜索(参数选择)
- Implement strStr()
- setAttribute和setParameter方法的区别
- 有关软件测试计划编写注意事项
- MongoDB总结
- 设计模式-结构型之适配器模式
- 编程可视化 - 数组排序过程在图像中的映射
- HDU 1025
- poj3254:玉米田的种植规划
- 有关翻页功能测用例设计