[LeetCode]Implement strStr()

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

思考:复习KMP算法。

class Solution {

public:

    char *strStr(char *haystack, char *needle) {

        // IMPORTANT: Please reset any member data you declared, as

        // the same Solution instance will be reused for each test case.

		int len1=strlen(haystack);

		int len2=strlen(needle);

		if(len1<len2) return NULL;

		if(len2==0) return haystack;

		vector<int> fail;

		fail.resize(len2+1,0);

		int i,j,k;

		j=0;k=-1;fail[0]=-1;

		while(j<len2)

		{

			if((k==-1)||(needle[j]==needle[k]))

			{

				j++;

				k++;

				if(needle[j]==needle[k])

					fail[j]=fail[k];

				else

					fail[j]=k;

			}

			else

				k=fail[k];

		}

		i=0;

		j=0;

		while(i<len1&&j<len2)

		{

			if(j==-1||haystack[i]==needle[j])

			{

				i++;

				j++;

			}

			else j=fail[j];

		}

		if(j==len2) return haystack+i-len2;

		else return NULL;

    }

};

      貌似VS2010上return NULL会报错:0x101cd540指令引用的0x00000000内存。该内存不能为read。 

你可能感兴趣的:(LeetCode)