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



你可能感兴趣的:([leetcode刷题系列]strStr)