码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode -- Implement strStr()

时间:2014-08-15 14:14:58      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   strong   for   ar   art   

反正总是有人要赢,那为什么不能是我呢~

 [问题描述]

Implement strStr().

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

[解题思路]

1.KMP. 2.暴力

 1 char *Solution::strStr(char* haystack, char* needle)
 2 {
 3     if (haystack == NULL || needle == NULL)
 4         return NULL;
 5     if (needle[0] == \0)
 6         return haystack;
 7     int next[strlen(needle)];//计算nextval
 8     int i = 0, j = -1;
 9     next[i] = -1;
10     while (needle[i] != \0){
11         if (j == -1 || needle[i] == needle[j]){
12             i++, j++; next[i] = j;
13         }
14         else{
15             j = next[j];
16         }
17     }
18     i = 0, j = 0;//匹配字符串
19     char* ans = NULL;
20     while (haystack[i] != \0){
21         while (j >= 0 && haystack[i] != needle[j])
22             j = next[j];
23         i++; j++;
24         if (needle[j] == \0){
25             ans = haystack + i - j;
26             return ans;
27         }
28     }
29     return ans;
30 }

暴力有效的方法1:

 1 char *strStr(char *haystack, char *needle)
 2  {
 3     if(needle == NULL) return haystack;
 4     else{
 5         int len1 =strlen(haystack),len2 = strlen(needle);
 6         if(len2 == 0) return haystack;
 7         for(int i = 0 ; i < len1-len2+1; ++ i){
 8             if(strncmp(haystack+i,needle,len2) == 0) return haystack+i;
 9         }
10         return NULL;
11     }
12 }

暴力有效的方法2:

 1 char *strStr(char *haystack, char *needle) 
 2 {
 3     int i,j;  
 4     for (i = j = 0; haystack[i] && needle[j];) {  
 5         if (haystack[i] == needle[j]) {  
 6             ++i;  
 7             ++j;  
 8         } else {  
 9             i = i - j + 1;  
10             j = 0;  
11         }  
12     }  
13     return needle[j] ? 0 : (haystack + i - j);  
14 }

 

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

leetcode -- Implement strStr()

标签:style   blog   color   io   strong   for   ar   art   

原文地址:http://www.cnblogs.com/taizy/p/3914581.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!