LeetCode 28. Implement strStr() - KMP

守給你的承諾、 提交于 2020-02-04 20:45:08

题目链接:28. Implement strStr()

Implement strStr().

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

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().

题解

双指针算法就是从匹配串的第一个字符开始一个一个的匹配,直到结束或找到为止。

KMP算法只写的出来代码,next数组的构造还理不清楚。

第一个KMP算法的题目,方便以后查找。

Java代码

暴力搜索算法(双指针)
class Solution {
	public int strStr(String source, String target) {
		if (target == null || target.equals("")) {
			return 0;
		}
		if (source == null || source.equals("")) {
			return -1;
		}

		char[] sourceArr = source.toCharArray();
		char[] targetArr = target.toCharArray();
		int sourceCount = sourceArr.length;
		int targetCount = targetArr.length;

		if (sourceCount < targetCount) {
			return -1;
		}

		int i = 0;
		int j = 0;
		while (i < sourceCount && j < targetCount) {
			if (sourceArr[i] == targetArr[j]) {
				++i;
				++j;
			} else {
				i = i - j + 1;
				j = 0;
			}
			if (j == targetCount) {
				return i - j;
			}
		}
		return -1;
	}
}
KMP算法
// 2020-2-4 16:31:19
class Solution {
	public int strStr(String source, String target) {
		if (target == null || target.equals("")) {
			return 0;
		}
		if (source == null || source.equals("")) {
			return -1;
		}

		char[] sourceArr = source.toCharArray();
		char[] targetArr = target.toCharArray();
		int sourceCount = sourceArr.length;
		int targetCount = targetArr.length;

		if (sourceCount < targetCount) {
			return -1;
		}

		// 构造二维数组next,next[i][j]=k表示已经匹配到i个字符,
		// 遇到字符j的时候,下一步的状态是k
		int[][] next = new int[targetCount][128];
		next[0][targetArr[0]] = 1;
		int index = 0;
		for (int i = 1; i < targetCount; ++i) {// 匹配串
			for (int j = 0; j < 128; ++j) {// 字符
				next[i][j] = next[index][j];// 检查相同前缀的状态
			}
			next[i][targetArr[i]] = i + 1;// 第i个字符匹配,状态加1
			index = next[index][targetArr[i]];// 更新最大前缀
		}

		// 查找
		index = 0;
		for (int i = 0; i < sourceCount; ++i) {
			index = next[index][sourceArr[i]];
			if (index == targetCount) {
				return i - (index - 1);
			}
		}
		return -1;// 未找到目标字符串
	}
}

原文链接:https://blog.csdn.net/pfdvnah/article/details/104171312

- End - wowpH - pfdvnah -
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!