题目

给你两个字符串 haystackneedle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1

示例 1:

1
2
3
4
输入:haystack = "sadbutsad", needle = "sad"
输出:0
解释:"sad" 在下标 0 和 6 处匹配。
第一个匹配项的下标是 0 ,所以返回 0 。

示例 2:

1
2
3
输入:haystack = "leetcode", needle = "leeto"
输出:-1
解释:"leeto" 没有在 "leetcode" 中出现,所以返回 -1 。

提示:

  • 1 <= haystack.length, needle.length <= 104
  • haystackneedle 仅由小写英文字符组成

我的解法

遍历每个字符,要是找到了第一个相同的字符就看看后边的字符匹不匹配就完事了,不匹配就继续找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <string>
using namespace std;
class Solution {
public:
int strStr(string haystack, string needle) {
int ret = -1;
auto hay = haystack.begin();
auto need = needle.begin();
while (hay != haystack.end())
{
if (*hay == *need)
{
ret = distance(haystack.begin(), hay);
// 开始逐个比较
for(int index = 1;index < needle.size();index++){
if(*(hay+index) != *(need+index))
{
ret = -1;
break;
}
}
}
if (ret != -1)
{
break;
}
hay++;
}
return ret;
}
};