28 实现strStr()
题目如下:给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
有点像数据结构串的应用。想着应用KMP算法解题,但不会写啊==。只能看了答案写出来这个:
首先是构造next函数:
vector<int> next(string str)
{
vector<int> v;
v.push_back(-1);//将一个元素插入vector的末尾。
int i = 0, j = -1;
while (i < str.size())
{
if (j == -1 || str[i] == str[j])
{
++i;
++j;
v.push_back(j);
}
else
j = v[j];
}
return v;
}
主函数:
int strStr(string haystack, string needle)
{
int i = 0;//主串位置
int j = 0;//模式串位置
int len1 = haystack.size(), len2 = needle.size();
vector<int> nextptr
if(needle.empty())
return 0;
nextptr = next(needle);
while((i < len1)&&(j < len2))
{
if((j == -1) || (haystack[i] == needle[j]))
//当j=-1时移动主串位置,相等的字符要跳过
{
i++;
j++;
}
else
{
j = nextptr[j];//获取下一个匹配位置
}
}
if (j == needle.size())
return i - j;
else
return -1;
}
};
执行后:

方法二:
运用内置find()函数:
1,返回字符(字符串)在原来字符串的中首次出现的下标位置
例:string s(“1a2b3c4d5e6f7g8h9i1a2b3c4d5e6f7g8ha9i”); position =
s.find(“jk”);2,返回flag 中任意字符 在s 中第一次出现的下标位置
flag = “c”; position = s.find_first_of(flag);
3,从字符串s 下标5开始,查找字符串b ,返回b 在s 中的下标
position=s.find(“b”,5);
4,查找flag 中与s 第一个不匹配的位置
flag=“acb12389efgxyz789”; position=flag.find_first_not_of (s);
5,反向查找,flag 在s 中最后出现的位置
flag=“3”; position=s.rfind (flag);
功能实现:
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.empty()) return 0;
int pos=haystack.find(needle);//在字符串haystack中查找needle
if(pos==-1) return -1;//未找到find()返回-1
return pos;
}
};
运行:

本文介绍如何在Python中实现strStr()函数,通过两种方法:使用KMP算法和利用内置的find()函数。文章详细讲解了构造next函数和主函数的过程,并给出了不同find()函数用法的实例。

被折叠的 条评论
为什么被折叠?



