Implement strStr()

题目描述:

https://leetcode-cn.com/problems/implement-strstr/

思路:字符串匹配,在源字串中找到和目标字串开头字母相等的位置,再依次向后比较,如果剩余的字母也相同,则返回该位置。就否则继续向后重复该操作,直到源字串完。

#include<cstdio>
#include<iostream> 
#include<string>
using namespace std;

int strStr(string haystack, string needle) 
{
	if(needle=="")
	    return 0;
	//源字串开头位置剩余字母数最低要和目标字串字母数相等 
        int limit = haystack.length()-needle.length();
	for(int i=0;i<=limit;++i)
	{
		int h_index = i;
		int n_index = 0;
		while(n_index<needle.length()&&haystack[h_index]==needle[n_index])
		{
			h_index += 1;
			n_index += 1;
		}
		//如果匹配成功返回位置 
		if(n_index==needle.length())
			return i;   
	}
	return -1;         
}
int main(){
	string haystack = "aaaaa"; 
	string needle = "bba";
	int result = strStr(haystack,needle);
	printf("%d\n",result);
	return 0;
}

注:字符串匹配的最佳做法其实是KMP算法,大家如果有兴趣可以去下面这个网址了解一下:https://www.cnblogs.com/c-cloud/p/3224788.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值