leetcode 原题链接:https://leetcode.com/problems/implement-strstr/
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
简要翻译:要求实现strStr()函数。返回在子字符串needle在字符串haystack中第一次出现的位置,如果没有找到则返回-1;
简要分析:此题不难,我采用的是比较普遍的做法,即依依去对比字符串是否完全相同;此种做法的思路比较简单,但是时间复杂度较高,为O(mn)。
需要注意的是,空字符串也算一个子串。
实现代码:
<span style="font-size:14px;">class Solution
{
public:
int strStr(string haystack, string needle)
{
if (haystack.size() < 0)
return -1;
if (needle.size() == 0)
return 0;
int j = 0;
//cout << haystack.size() << " " << needle.size() << " " << endl;
//int lenght = haystack.size() - needle.size() + 1;
for (int i = 0; i < (int)(haystack.size() - needle.size() + 1); i++)
{
cout << "i = " << i << endl;
if (haystack[i] == needle[j])
{
int k = i;
for (; j < needle.size(); j++)
{
if (haystack[k] == needle[j])
{
k++;
} else
{
j = 0;
break;
}
}
if (j == needle.size())
{
return i;
}
}
}
return -1;
}
};</span>