Implement strStr() leetcode

本文介绍了一种通过遍历字符串来查找子串首次出现位置的方法。该方法适用于暴力破解方式解决strStr()函数问题,即返回子串在主串中首次出现的索引位置。

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

Implement strStr().

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

Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button  to reset your code definition.

 

解题:我用的方法相当于暴力破解:int strStr(string haystack, string needle) ;

  首先,遍历haystack,依次寻找第一个与needle第一个字符匹配的位置,同时记录相对于该位置的下一个位置(我记为ret,一旦接下来的匹配不成功,重新遍历haystack时,就从ret开始),如果遍历完haystack都没匹配成功,则返回-1。注意边界条件!!

  我的源代码如下:

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

 

转载于:https://www.cnblogs.com/chess/p/4896520.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值