题目描述:
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