您的位置:首页 > 其它

LeetCode - Implement strStr()

2014-02-28 02:42 316 查看
Implement strStr()

2014.2.28 02:38

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

Solution1:

  The first one is brute-force, reference is from source code of strstr() in <string.h>.

  Total time complexity is O(n * m). Space complexity is O(1).

Accepted code:

// 1WA, 1AC, standard Brute-Force solution.
#include <cstring>
using namespace std;

class Solution {
public:
char *strStr(char *haystack, char *needle) {
const char *ptr = haystack;
size_t len = strlen(needle);
if (len == 0) {
return haystack;
}
while ((ptr = strchr(ptr, *needle)) != nullptr) {
if (strncmp(ptr, needle, len) == 0) {
return (char *)ptr;
}
++ptr;
}
}
};


Solution2:

  This solution uses KMP Algorithm, which runs in linear time.

  The key difference between KMP and Brute-Force is the "next" array, that defines the position to backtrack when mismatch happens.

  Here is the reference from Wikipedia of KMP Algorithm, if you'd like to learn more about it.

  Total time complexity is O(len(haystack) + len(needle)). Space complexity is O(needle).

Accepted code:

// 2CE, 1RE, 1WA, 1AC, KMP Algorithm
#include <cstring>
#include <vector>
using namespace std;

class Solution {
public:
char *strStr(char *haystack, char *needle) {
if (haystack == nullptr || needle == nullptr) {
return nullptr;
}
lp = strlen(needle);
lw = strlen(haystack);

if (lp == 0) {
return haystack;
}

if (lw < lp) {
return nullptr;
}

calculateNext(needle);
char *result = KMPMatch(haystack, needle);
next.clear();

return result;
}
int lp;
private:
int lw;
vector<int> next;

void calculateNext(char *pat) {
int i = 0;
int j = -1;

next.resize(lp + 1);
next[0] = -1;
while (i < lp) {
if (j == -1 || pat[i] == pat[j]) {
++i;
++j;
next[i] = j;
} else {
j = next[j];
}
}
}

char* KMPMatch(char *word, char *pat)
{
int index;
int pos;

index = pos = 0;
while (index < lw) {
if (pos == -1 || word[index] == pat[pos]) {
++index;
++pos;
} else {
pos = next[pos];
}

if (pos == lp) {
// the first match is found
return word + (index - lp);
}
}

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