Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char *
or String
, please click the reload button to reset your code definition.
笨办法,从开头检查到尾,
O(nm) runtime, O(1) space
改进的方法应该是O(n),前面转载了一个博客,有更好的方法。
// test28ImplementstrStr.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "string"
using std::string;
int strStr(string haystack, string needle);
int _tmain(int argc, _TCHAR* argv[])
{
string s1 = "haha";
string s2 = "jhajdfhahhha";
int i = strStr(s2, s1);
return 0;
}
int strStr(string haystack, string needle)
{
int num1 = haystack.size();
int num2 = needle.size();
if (num1 < num2)
return -1;
if (num2 == 0)
return 0;
for (int i = 0; i <= num1 - num2; i++)
{
if (haystack[i] == needle[0])
{
string temp(haystack,i,num2);
if (temp==needle)
return i;
}
}
return -1;
}
//
#include "stdafx.h"
#include "string"
using std::string;
int strStr(string haystack, string needle);
int _tmain(int argc, _TCHAR* argv[])
{
string s1 = "haha";
string s2 = "jhajdfhahhha";
int i = strStr(s2, s1);
return 0;
}
int strStr(string haystack, string needle)
{
int num1 = haystack.size();
int num2 = needle.size();
if (num1 < num2)
return -1;
if (num2 == 0)
return 0;
for (int i = 0; i <= num1 - num2; i++)
{
if (haystack[i] == needle[0])
{
string temp(haystack,i,num2);
if (temp==needle)
return i;
}
}
return -1;
}