题目:
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.
链接:https://oj.leetcode.com/problems/implement-strstr/
描述:实现字符串查找算法
解法:除了暴力的BF算法,常见实现有KMP,BM,Rabin-karp算法,这里实现了sunday算法,平均效果据说优于KMP和BM
solution by python:
class Solution:
# @param haystack, a string
# @param needle, a string
# @return an integer
def strStr(self, haystack, needle):
index_map = {}
hlen = len(haystack); nlen=len(needle)
for i in range(nlen):
index_map[needle[i]] = nlen-i
hidx=nlen-1; nidx=nlen-1
while hidx < hlen:
same = True
for i in range(nlen):
if haystack[hidx-i] != needle[nidx-i]:
same = False
break
if same: return hidx-nlen+1
hidx += nlen if hidx==hlen-1 or haystack[hidx+1] not in index_map else index_map[haystack[hidx+1]]
return -1
solution by c++:
kmp算法实现
class Solution {
public:
char *strStr(char *haystack, char *needle) {
int hlen = strlen(haystack);
int nlen = strlen(needle);
if(hlen < nlen) return NULL;
int *shift = new int[nlen];
shift[0]=-1;
for(int i=1; i<nlen; i++)
{
int idx = shift[i-1];
while(idx!=-1 && needle[i]!=needle[idx+1] )
idx = shift[idx];
if(needle[i] == needle[idx+1])
shift[i] = idx+1;
else shift[i] = -1;
}
int hidx=0,nidx=0;
while(hidx<hlen && nidx<nlen)
{
if(haystack[hidx] == needle[nidx])
{
hidx++;nidx++;
}
else if(nidx==0) hidx++;
else
{
nidx=shift[nidx-1]+1;
}
}
delete []shift;
if(nidx == nlen)
{
return haystack+hidx-nidx;
}
return NULL;
}
};