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

Leetcode -- 28. Implement strStr()

2017-04-21 08:52 363 查看

题目:Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

思路:本题是让找到一个字符串是不是另一个字符串的子串,如果是就返回下标,如果不是返回-1。暴力比较,时间复杂度:O(mn)。

C++代码如下:

int strStr(string haystack, string needle) {
if (haystack.length() < needle.length())
return -1;
if (needle.empty())
return 0;
bool flag = true;
for (int i = 0; i <= haystack.length() - needle.length(); i++)
{
if (haystack[i] == needle[0])
{
flag = true;
for (int j = 1; j < needle.length(); j++)
{
if (haystack[i + j] != needle[j])
{
flag = false;
break;
}
}
if (flag)
return i;
}
}
return -1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode c-c++