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