LeetCode 28 Implement strStr()

题意:

给出字符串s和p,找出p在s中第一次出现的位置。如果p没出现过,则输出-1。


思路:

这是一个kmp裸题,学习kmp建议 http://blog.csdn.net/v_july_v/article/details/7041827 。相比next版本,nextval版本更好。

当然C++中string还提供的find功能可以偷懒。


代码:

/**
 * kmp 版本
 */
class Solution {
public:
    int strStr(string haystack, string needle) {
        if (needle.size() == 0) {
            return 0;
        }
        int const slen = haystack.size(), plen = needle.size();
        int next[plen];
        get_nextval(needle, plen, next);
        return kmp(haystack, slen, needle, plen, next, 0);
    }

private:
    void get_nextval(string ptrn, int plen, int *nextval) {
        int i = 0;
        nextval[i] = -1;
        int j = -1;
        while (i < plen) {
            if (j == -1 || ptrn[i] == ptrn[j]) {
                ++i;
                ++j;
                if (ptrn[i] != ptrn[j]) nextval[i] = j;
                else nextval[i] = nextval[j];
            } else j = nextval[j];
        }
    }

    int kmp(string src, int slen, string patn, int plen, int const *nextval, int pos) {
        int i = pos;
        int j = 0;
        while (i < slen && j < plen) {
            if (j == -1 || src[i] == patn[j]) {
                ++i;
                ++j;
            } else j = nextval[j];
        }
        if (j >= plen) return i - plen;
        else return -1;
    }
};

/**
 * 偷懒版本……
 */

class Solution {
public:
    int strStr(string haystack, string needle) {
        if (needle.size() == 0) {
            return 0;
        }
        return haystack.find(needle);
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值