首页 > 其他 > 详细

Implement strStr()

时间:2014-04-19 15:48:20      阅读:494      评论:0      收藏:0      [点我收藏+]
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.

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     char *strStr(char *haystack, char *needle) {
 4         char *i = haystack;
 5         char *j = needle;
 6         int k = 0, m = 0;
 7         if (*j==\0)return haystack;
 8         while (*i != \0){
 9             while (*(i+k)!=\0 && *(j+m)!=NULL && *(i+k) == *(j+m)){
10                 k++;
11                 m++;
12             }
13             if (k!=0 && m!= 0){
14                 if (*(j+m) == \0){
15                     return i;
16                 }else{
17                     k=0;m=0;
18                 }
19             }
20             i++;
21         }
22         return NULL;
23     }
24 };
bubuko.com,布布扣

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:

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     char *strStr(char *haystack, char *needle) {
 4         char *i = haystack;
 5         char *j = needle;
 6         char *l = haystack;
 7         int k = 0;
 8         if (!*j)return haystack;
 9         
10         while (*++j){
11             l++;
12         }
13         j = needle;
14         
15         while (*l){
16             while (*(i+k) && *(j+k) && *(i+k) == *(j+k)){
17                 k++;
18             }
19             if (k!=0){
20                 if (!*(j+k)){
21                     return i;
22                 }else{
23                     k=0;
24                 }
25             }
26             i++;
27             l++;
28         }
29         return NULL;
30     }
31 };
bubuko.com,布布扣

 

 

Implement strStr(),布布扣,bubuko.com

Implement strStr()

原文:http://www.cnblogs.com/agentgamer/p/3674571.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!