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。KMP的精髓是写一个next函数,当失配的时候,算出后移多少位再匹配,这样可以提升匹配的效率。

#include <iostream>
using namespace std;

class Solution{
public:
	//暴力破解
	char *strStr(char*haystack,char*needle)
	{
		if(!*needle) return (char*) haystack;
		int len_haystack = strlen(haystack);
		int len_needle = strlen(needle);
		int j;

		for(int i=0;i<=len_haystack - len_needle;i++)
		{
			for(j=0;j<len_needle;j++)
			{
				if(needle[j] != haystack[i+j])
				{
					break;
				}				
			}

			if(j == len_needle)
					return haystack+i;
		}
		return NULL;
	}
};

void main()
{
	char*haystack ="bcd";
	char*needle = "bcd";

	Solution sol;
	char *c = sol.strStr(haystack,needle);
	if(c!=NULL)
	{
		printf("The occurence is %c\n",*c);
	}
	else
		printf("No string include!\n");
}



你可能感兴趣的:(Implement strStr())