leetcode Implement strStr()

题目连接

https://leetcode.com/problems/implement-strstr/  

Implement strStr()

Description

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

kmp水一发。。

class Solution {
public:
	void get_next(string needle) {
		next.push_back(0);
		for (size_t i = 1, j = 0; i < n; i++) {
			while (j > 0 && needle[i] != needle[j]) j = next[j - 1];
			if (needle[i] == needle[j]) j++;
			next.push_back(j);
		}
	}
	int kmp(string haystack, string needle) {
		for (size_t i = 0, j = 0; i < m; i++) {
			while (j > 0 && haystack[i] != needle[j]) j = next[j - 1];
			if (haystack[i] == needle[j]) j++;
			if (j == n) return i - n + 1;
		}
		return -1;
	}
	int strStr(string haystack, string needle) {
		n = needle.length();
		m = haystack.length();
		if((!n && !m) || !n) return 0;
		if(!m && n) return -1;
		get_next(needle);
		return kmp(haystack, needle);
	}
private:
	size_t n, m;
	vector<int> next;
};
posted @ 2015-12-11 20:53  GadyPu  阅读(124)  评论(0编辑  收藏  举报