码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode Implement strStr()

时间:2015-12-11 22:06:13      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

题目连接

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

leetcode Implement strStr()

标签:

原文地址:http://www.cnblogs.com/GadyPu/p/5040199.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!