28. Implement strStr()

本文介绍了一种使用KMP算法实现字符串匹配的方法,即寻找子串在主串中首次出现的位置。通过详细的C++代码示例展示了如何构建next数组来加速匹配过程。

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

 

判断子串needle 在主串haystack中首次出现的位置

 

C++(6ms):   KMP算法

 1 class Solution {
 2 public:
 3     vector<int> getNext(string needle , int tlen){
 4         int j, k;
 5         vector<int> Next(tlen+1, 0);
 6         j = 0; k = -1; Next[0] = -1;
 7         while(j < tlen)
 8             if(k == -1 || needle[j] == needle[k])
 9                 Next[++j] = ++k;
10             else
11                 k = Next[k];
12         return Next ;
13     }
14     
15     int strStr(string haystack, string needle) {
16         int slen = haystack.size() ;
17         int tlen = needle.size() ;
18         if (!tlen)
19             return 0 ;
20         vector<int> Next = getNext(needle,tlen) ;
21         int i = 0, j = 0;
22         while(i < slen && j < tlen)
23         {
24             if(j == -1 || haystack[i] == needle[j])
25             {
26                 i++; j++;
27             }
28             else
29                 j = Next[j];
30         }
31         if(j == tlen)
32             return i - tlen ;
33         else
34             return -1;
35     }
36 };

 

转载于:https://www.cnblogs.com/mengchunchen/p/7735619.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值