您的位置:首页 > 其它

(算法分析Week6)Implement strStr()[Easy]

2017-10-14 13:31 232 查看

28. Implement strStr()

Description

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

也就是字符串模式匹配,返回第一个对应匹配的下标。

Solution

KMP算法,具体可以看这篇博客

Complexity analysis

O(n+m)

Code

class Solution {
public:
void Next(int* &next, string pattern) {
next[0] = -1;
int k = -1;
int j = 0;
int n = pattern.length();
while (j < n - 1) {
if (k == -1 || pattern[j] == pattern[k]) {
j++;
k++;
next[j] = k;
cout << next[j];
}
else {
k = next[k];
}

}
}
int strStr(string haystack, string needle) {

int length = needle.length();
int *arr = new int[length];
/*一个基础知识的吐槽,是[]不是(),否则delete对应会出错*/

Next(arr, needle);

int i, j;
i = j = 0;
while (i < haystack.length() && j < (int)needle.length()) {
/*这里要注意,string.length()是一个无符号数!当j=-1与其比较,会返回大于的结果,直接跳出循环
一直不过就是因为这里,IDE跑的时候warning才发现
*/
if (j == -1 || haystack[i] == needle[j]) {
i++;
j++;
}
else {
j = arr[j];
}
}
delete []arr;
if (j >= needle.length()) {
return i - needle.length();
}
return -1;

}
};


Result

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: