问题:
给你两个字符串 haystack
和 needle
,请你在 haystack
字符串中找出 needle
字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle
不是 haystack
的一部分,则返回 -1
。
#include<iostream>
#include<string>
using namespace std;
class Solution
{
public:
int kt = -2;
int count = 0;
int strStr(string haystack, string needle)
{
for (int i = 0; i < haystack.size(); i++)
{
if (kt >= 0)
{
break;
}
count = 0;
int k = i;
for (int j = 0; j < needle.size(); j++)
{
if (haystack[k] == needle[j])
{
count++;
k++;
if (count == needle.size()) //mississipi issip
{
kt = k-needle.size();
//return kt;
}
}
}
}
if (kt == -2)
return -2;
else
return kt;
}
};
int main()
{
Solution d;
string haystack = "mississippi";
string needle = "issip";
int kt=d.strStr(haystack, needle);
cout << kt;
return 0;
}