您的位置:首页 > 编程语言 > C语言/C++

[C++]Implement strStr() 找到子字符串第一次出现的位置

2015-08-23 20:14 405 查看
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
4000
= 0;
break;
}
}
if (j == needle.size())
{
return i;
}
}
}
return -1;
}
};</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息