LeetCode:Implement strStr()

本文详细介绍了两种常用的字符串匹配算法——暴力破解法与KMP算法。通过具体的代码实现展示了如何找到一个字符串在另一个字符串中首次出现的位置。适用于解决LeetCode等平台上的字符串查找问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

problem:

Implement strStr().

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

此题目实质为字符串匹配问题,其中比较高效的算法是KMP算法 它相对于暴力破解算法比较成功的找到了有效的回溯位置。

解法一:暴力破解

 1 class Solution {
 2 public:
 3     int strStr(string haystack, string needle) {
 4         int slen=haystack.size();
 5         int plen=needle.size();
 6         
 7         int i=0;
 8         int j=0;
 9         for(;i<slen&&j<plen;)
10         {
11             if(haystack[i]==needle[j])
12             {
13                 i++;j++;
14             }
15             else{   //匹配不成功回溯  j重置
16                 i=i-j+1;
17                 j=0;
18             }
19         }
20         if(j==plen)
21            return i-j;
22          else
23           return -1;
24     }
25 };

 解法二:kmp

 1 class Solution {
 2 public:
 3     int strStr(string s, string p) {
 4         //kmp算法
 5         
 6         if(!p.size()||!s.size()) return 0;
 7         vector<int> next(p.size(),0);
 8         int plen=p.size();
 9         int slen=s.size();
10         computeNext(next,p,plen);
11         int j;int i;
12         for(i=0;i<slen;i++)
13             for(j=0;j<plen;j++)
14             {
15                 if(s[i]==p[j])
16                 {
17                     i++;j++;
18                 }
19                 else{
20                     j=next[j];
21                 }
22                 
23             }
24           if(j==plen) return i-j;
25           else return -1;
26         
27     }
28     
29     
30     void computeNext(vector<int> &next,string &p,int &plen)
31     {
32         
33         int q=next[0]=-1;
34         
35         int j=0;
36         plen--;
37         while(j<plen)
38         {
39             if(q==-1||p[q]==p[j])
40                 next[++j]=++q;
41             else 
42                 q=next[q];
43             
44         }
45     }
46     
47 };

 

          

转载于:https://www.cnblogs.com/xiaoying1245970347/p/4556148.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值