问题:
实现 strStr() 函数。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。当 needle
是空字符串时我们应当返回 0 。
示例 1:
输入:haystack = "hello", needle = "ll"
输出:2
示例 2:
输入:haystack = "aaaaa", needle = "bba"
输出:-1
示例 3:
输入:haystack = "", needle = ""
输出:0
解答:
方法一:暴力匹配
遍历haystack字符串,直到找到一个与needle字符串的首位的下标作为【起始点】,然后开始逐个比较尝试匹配。
- 匹配成功:返回起始点下标。
- 匹配失败:回到起始点的下一位,继续尝试匹配。
代码如下:
int strStr(string haystack, string needle)
{
if (needle.empty())
return 0;
int i = 0, j = 0;
while (i < haystack.length() && j < needle.length())
{
if (haystack[i] == needle[j])
i++, j++;
else
{
i = i - j + 1;
j = 0;
}
}
if (j == needle.length())
return i - j;
else
return -1;
}