Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
class Solution {
public:
char *strStr(char *haystack, char *needle) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
unsigned int len_h = strlen(haystack);
unsigned int len_n = strlen(needle);
if(len_n == 0) {
return haystack;
}
for(unsigned int i = 0; i < len_h; ++ i) {
unsigned int t = i, j = 0;
while(t < len_h && j < len_n) {
if(i + len_n > len_h) break;
//if(len_n)
if(*(haystack + t) != *(needle + j) ||
*(haystack + len_n + 2 * i - t - 1) != *(needle + len_n - j - 1)) {
break;
}
++ t;
++ j;
}
if(j == len_n) {
return haystack + i;
}
}
return NULL;
}
};
坑:
裸暴力不让过,加个小优化(头部和尾部同时对比)。为啥不用kmp?,因为忘光了。
没有评论:
发表评论