问题描述:
实现 strStr() 函数。给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。当
needle
是空字符串时我们应当返回 0。
示例: 输入:haystack = "hello", needle = "ll" 输出:2 输入:haystack = "aaaaa", needle = "bba" 输出:-1 输入:haystack = "", needle = "" 输出:0
解题思路:
思路①:首先我们会想到设置两个变量来遍历字符串,不相同的时候,指向haystack的变量往后遍历,但是有一个问题是,当前边部分字符串对应相同时,等遍历到不相同的字符串时,我们需要返回从第一个相同字符串的下一个位置开始重新遍历,指向needle的变量从头开始。这个时候,我们就再需要两个变量来记录这些位置。画图分析:
代码实现
int strStr(string haystack, string needle)
{
int i = 0;
int j = 0;
int starth = i;
int startn = j;
if (needle.size() == 0)
{
return 0;
}
while (i < haystack.size())
{
i = starth;
j = startn;
while (i < haystack.size() && j < needle.size() && haystack[i] == needle[j])
{
i++;
j++;
}
if (j == needle.size())
{
return starth;
}
if (i == haystack.size())
{
return -1;
}
starth++;
}
return -1;
}
思路②:设置两个变量来遍历字符串,当变量所指向的字符相同时,i++,j++,当指向的变量不相同时i = i - j + 1; j=0;最后返回的结果是i-j。其实两种思路大致相同,只是第一种方法用了两个变量来记录了重新遍历的位置。画图分析
int strStr(string haystack, string needle) {
if (needle.empty())
{
return 0;
}
int i = 0, j = 0;
while (haystack[i] != '\0' && needle[j] != '\0')
{
if (haystack[i] == needle[j])
{
i++;
j++;
}
else
{
i = i - j + 1;
j = 0;
}
}
if (needle[j] == '\0')
{
return i - j;
}
return -1;
}