[leetcode]Implement strStr()

题目:

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

算法介绍详见:http://baike.baidu.com/link?url=Stl5E7_oQN719eEWTpV71f1noupdzH1E3HPy_WSzQkIz_buu3dBjnm9Uug487MyRS5rXg1Yz7nHf2AjrdN5Ika

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;
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值