您的位置:首页 > 编程语言 > C语言/C++

leetcode笔记:Implement strStr()

2015-10-09 23:40 375 查看
一.题目描述

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。由于使用暴力方法的时间复杂度为O(mn)会超时,可使用著名的KMP算法解决。该是由Knuth,Morris,Pratt共同提出的字符串匹配算法,其对于任何字符串和目标字符串,都可以在线性时间内完成匹配查找,是一个非常优秀的字符串匹配算法。

三.示例代码

KMP算法:

class Solution {
public:
void getNext(vector<int> &next, string &needle) {
int i = 0, j = -1;
next[i] = j;
while (i != needle.length()) {
while (j != -1 && needle[i] != needle[j]) j = next[j];
next[++i] = ++j;
}
}
int strStr(string haystack, string needle) {
if (haystack.empty()) return needle.empty() ? 0 : -1;
if (needle.empty()) return 0;
vector<int> next(needle.length() + 1);
getNext(next, needle);
int i = 0, j = 0;
while (i != haystack.length()) {
while (j != -1 && haystack[i] != needle[j]) j = next[j];
++i; ++j;
if (j == needle.length()) return i - j;
}
return -1;
}
};


四.小结

对于这题,还有其他一些有名的算法,如Rabin-Karp和Boyer-Moore算法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息