[leetcode刷题系列]strStr

字符串匹配问题把, 线性的算法显然是kmp了。 不过这题貌似可以暴力过, 所以这里给出两个版本, 一个暴力的, 一个kmp的。

先贴上一般的。

class Solution {
public:
    char *strStr(char *haystack, char *needle) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int lena = strlen(haystack);
        int lenb = strlen(needle);
        for(int i = 0; i + lenb - 1 < lena; ++ i){
            bool ok = true;
            for(int j = 0; ok && j < lenb; ++ j)
                if(haystack[i + j] != needle[j])
                    ok = false;
            if(ok)
                return haystack + i;
        }
        return 0;
    }
};


然后是kmp的

const int MAXN = 1e6 + 10;
template < class type >
void makefail( type *s, int len, int *fail){// s[0] - s[ken - 1]
    int now ;
	now = fail[0] = -1;
	for(int i = 1; i < len; ++ i){
		while( now >= 0 )
			if( s[now + 1] != s[i] ) now = fail[now]; else break;
		if( s[now + 1]  == s[i] ) ++ now;
		fail[i] = now;
	}
}

int fail[MAXN];
template < class type >
int kmp( type *text, int tlen, type *pat, int plen ){
	int ret = 0;
	makefail(pat, plen, fail);
	int now = -1;
	for( int i = 0; i < tlen; ++ i )
	{
		while( now >= 0 )
			if( text[i] != pat[now + 1] ) now = fail[now]; else break;
		if( text[i] == pat[now + 1] ) ++ now;
		
		if( now == plen - 1 )
			return i - plen + 1;
	}
	return -1;
}
class Solution {
public:
    char *strStr(char *haystack, char *needle) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(*needle == 0)
            return haystack;
        int lena = strlen(haystack);
        int lenb = strlen(needle);
        int ret = kmp(haystack, lena, needle, lenb);
        if(ret == -1)
            return 0;
        return haystack + ret;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值