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();
if (sourceArr.length < targetArr.length) {
// 源字符串长度小于目标字符串长度,肯定找不到
return -1;
}
// 构造二维数组next,next[i][j]=k表示已经匹配到i个字符,遇到字符j的时候,
// 下一步的状态是k
int[][] next = new int[targetArr.length][128];
// 匹配到0个字符并且遇到目标字符串的第0个字符时,状态改为1
next[0][targetArr[0]] = 1;
int index = 0;
// for循环遍历目标字符串,构造next数组
for (int i = 1; i < targetArr.length; ++i) {
// for循环遍历遇见的字符的128种情况
for (int j = 0; j < 128; ++j) {
// 检查相同前缀的状态
next[i][j] = next[index][j];
}
// 第i个字符匹配,状态加1
next[i][targetArr[i]] = i + 1;
// 更新最大前缀
index = next[index][targetArr[i]];
}
// 查找
index = 0;
for (int i = 0; i < sourceArr.length; ++i) {
index = next[index][sourceArr[i]];
if (index == targetArr.length) {
return i - (index - 1);
}
}
return -1;// 未找到目标字符串
}
}
原文链接:https://blog.csdn.net/pfdvnah/article/details/104171312