您的位置:首页 > 其它

【leetcode KMP算法实现】Implement strStr()

2014-08-31 21:51 465 查看
题目:

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

解析:实现strStr()方法,给定字符串haystack和needle,返回在haystack中第一次出现needle的位置。该题的一般解法非常简单,将haystack中的每个字符开头的子串和needle进行比对,如果相等即返回该字符开头的子串。该算法的时间复杂度为O(m*n),m为haystack的长度,n为needle的长度。

我用KMP算法实现该字符串比对问题,首先针对模式串needle求出它的next数组,然后再遍历haystack字符串。

Java AC代码如下:

public class Solution {

	public String strStr(String haystack, String needle) {
		if (haystack == null || needle == null) {
			return null;
		}
		int[] next = getNext(needle);

		int pS = 0, pH = pS, pN = 0;
		while (pS + needle.length() <= haystack.length()) {
			if (pN == needle.length()) {
				return haystack.substring(pS);
			} else if (haystack.charAt(pS + pH) == needle.charAt(pN)) {
				pH++;
				pN++;
			} else if (next[pN + 1] == 0) {
				pH = pN = 0;
				pS++;
			} else {
				pH -= (pN - next[pN]);
				pS += (pN - next[pN]);
				pN = next[pN];
			}
		}
		return null;
	}

	public static int[] getNext(String needle) {
		int[] next = new int[needle.length() + 1];
		next[0] = -1;
		needle = '$' + needle;
		for (int i = 1; i < needle.length(); i++) {
			if (next[i - 1] == 0) {
				next[i] = needle.charAt(i) == needle.charAt(1) ? 1 : 0;
			} else {
				int before = next[i - 1];
				while (before != -1) {
					if (needle.charAt(before + 1) == needle.charAt(i)) {
						next[i] = before + 1;
						break;
					} else {
						before = next[before];
					}
				}
			}
		}
		return next;
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: