题目: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;
}