28.Implement strStr
查找子串
注意特殊情况:子串全部等于母串,返回0;子串为空或不存在返回-1;
#include <iostream>
#include <vector>
#include <map>
using namespace std;
int strStr(string haystack, string needle) {
if(needle.length()==0 ||haystack==needle)
{
return 0;
}
if(haystack.length()<=needle.length())
{
return -1;
}
for(int i=0;i<haystack.length()-needle.length()+1;i++)
{
bool successFlag=true;
for(int j=0;j<needle.length();j++)
{
cout<<haystack[i+j]<<" "<<needle[j]<<endl;
if(haystack[i+j]!=needle[j])
{
successFlag=false;
break;
}
}
if(successFlag)
return i;
}
return -1;
}
int main(int argc, const char * argv[]) {
// insert code here...
string haystack,needle;
cin>>haystack;
cin>>needle;
cout<<strStr(haystack,needle)<<endl;
return 0;
}