首页 > 其他 > 详细

leetcode Implement strStr()

时间:2015-12-11 22:03:55      阅读:177      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!