您的位置:首页 > 其它

[LeetCode] Implement strStr()

2014-04-19 08:50 316 查看
Implement strStr().

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


I wrote that function before in practice without knowing anything about strStr(), so I have a pretty clear brute-force solution in my mind.

class Solution {
public:
char *strStr(char *haystack, char *needle) {
char *i = haystack;
char *j = needle;
int k = 0, m = 0;
if (*j=='\0')return haystack;
while (*i != '\0'){
while (*(i+k)!='\0' && *(j+m)!=NULL && *(i+k) == *(j+m)){
k++;
m++;
}
if (k!=0 && m!= 0){
if (*(j+m) == '\0'){
return i;
}else{
k=0;m=0;
}
}
i++;
}
return NULL;
}
};


Not very clean, with some unnecessary variable but express my thought well, unfortunately it's Time Limit Exceeded, means we can still do some optimize.
Some people says using KMP can definitely solve the problem, but its too hard to code(for me). I don't think people will ask to write KMP during an interview.
Then I find this thread the trick is, in fact we should aways only iterate N-M+1 times.

my AC version:

class Solution {
public:
char *strStr(char *haystack, char *needle) {
char *i = haystack;
char *j = needle;
char *l = haystack;
int k = 0;
if (!*j)return haystack;

while (*++j){
l++;
}
j = needle;

while (*l){
while (*(i+k) && *(j+k) && *(i+k) == *(j+k)){
k++;
}
if (k!=0){
if (!*(j+k)){
return i;
}else{
k=0;
}
}
i++;
l++;
}
return NULL;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: