28. Implement strStr()
- Total Accepted: 146121
- Total Submissions: 546205
- Difficulty: Easy
- Contributors: Admin
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Subscribe to see which companies asked this question
代码:
class Solution {
public: int f[ 150000];
void getfill(string t)
{
f[0]=-1;
int j=0;
int k=-1;
while(j<t.size())
if(k==-1||t[j]==t[k])
{
f[++j]=++k;
}
else k=f[k];
}
public:
int strStr(string s,string t)
{
int slen=s.length();
int tlen=t.length();
int i=0;
int j=0;
getfill(t);
while(i<slen&&j<tlen)
{
if(j==-1||s[i]==t[j])
{
i++;
j++;
}
else j=f[j];
}
if(j==tlen)
return i-tlen;
else return -1;
}
};