leetcode -- Implement strStr()

本文提供了两种实现strStr()函数的有效方法,一种是使用KMP算法进行字符串匹配,另一种是通过暴力匹配的方式寻找子串在主串中的位置。无论采用哪种方法,都能找到子串首次出现的位置。

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

 [问题描述]

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 }

 

转载于:https://www.cnblogs.com/taizy/p/3914581.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值