您的位置:首页 > 其它

LeetCode 28. Implement strStr()

2016-04-24 23:48 253 查看
Implement strStr().

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

It is pretty hard to generalize KMP algorithm under stress and limited time. Better to formalize brute force first and then move forward to KMP.

#include <string>
#include <iostream>
#include <vector>
using namespace std;

// brute force
int strStr(string haystack, string needle) {
int m = haystack.size();
int n = needle.size();
int i = 0, j = 0;
while(i < m && j < n) {
if(haystack[i] == needle[j]) {
i++;
j++;
} else {
i = i - j + 1;
j = 0;
}
}
return j == n ? i - j : -1;
} // time complexity: O(m*n)

// KMP to make the time complexity to be O(m + n);
vector<int> next(string& needle) {
vector<int> next(needle.size(), 0);
for(int i = 1; i < needle.size(); ++i) {
int j = next[i-1];
while(j > 0 && (needle[i] != needle[j])) j = next[j-1];
next[i] = (j + (needle[i] == needle[j]));
}
return next;
}

int strStrII(string haystack, string needle) {
vector<int> nextV = next(needle);
int k = 0;
for(int i = 0; i < haystack.size(); ++i) {
while(k > 0 && haystack[i] != needle[k]) k = nextV[k-1];
if(haystack[i] == needle[k]) k++;
if(k == needle.size()) return i - needle.size() + 1;
}
return -1;
}


One Variation in Facebook interview.

/*
StrStr variation.
implement function strstr(string a, string b) return index where any permutation
of b is a substring of a.
eg:
strstr("hello", "ell") return 1
strstr("hello", "lle") return 1
strstr("hello", "wor") return -1;
*/
void permutate(string target, string path, set<string>& res) {
if(target.size() == 0) {
res.insert(path);
return;
}
for(int i = 0; i < target.size(); ++i) {
string remains = target.substr(0, i) + target.substr(i + 1);
permutate(remains, path + target[i], res);
}
}
set<string> permutate(string target) {
string path = "";
set<string> res;
permutate(target, path, res);
return res;
}

int strstr(string orig, string target) {
set<string> perm = permutate(target);
auto iter = perm.begin();
int k = target.size();
for(int i = 0; i < orig.size() - k; ++i) {
string tmp = orig.substr(i, k);
if(perm.find(tmp) != perm.end()) return i;
}
return -1;
}

int main(void) {
cout << strstr("hello", "ell") << endl;
cout << strstr("hello", "lle") << endl;
cout << strstr("hello", "wor") << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: