今天又是坚持刷题的一天哦~
一、题目
给你两个字符串 haystack
和 needle
,请你在 haystack
字符串中找出 needle
字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle
不是 haystack
的一部分,则返回 -1
。
二、示例:
示例 1:
输入:haystack = "sadbutsad", needle = "sad" 输出:0 解释:"sad" 在下标 0 和 6 处匹配。 第一个匹配项的下标是 0 ,所以返回 0 。
示例 2:
输入:haystack = "leetcode", needle = "leeto" 输出:-1 解释:"leeto" 没有在 "leetcode" 中出现,所以返回 -1 。
提示:
1 <= haystack.length, needle.length <= 104
haystack
和needle
仅由小写英文字符组成
三、题解
/**
*
*28. 找出字符串中第一个匹配项的下标
* 相关企业
* 给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。
* @param haystack
* @param needle
* @return
*/
public int strStr(String haystack, String needle) {
//思路二 kmp
int[] next = new int[needle.length()];
getNext(next, needle);
int index = 0;
for (int i = 0; i < haystack.length(); i++) {
if (haystack.charAt(i) == needle.charAt(index)) {
index++;
if (index == needle.length()) {
return i - index + 1;
}
} else if (index > 0) {
index = next[index - 1];
i--;
}
}
return -1;
}
/**
*
* 获取前缀表
*
* @param next
* @param str
*/
public void getNext(int[] next, String str) {
int j = 0;
//初始化
next[0] = 0;
for (int i = 1; i < str.length(); i++) {
//一下while 和 if 的顺序不可以反
while (j > 0 && str.charAt(i) != str.charAt(j)) {
j = next[j - 1];
}
if (str.charAt(i) == str.charAt(j)) {
j++;
}
next[i] = j;
}
}
四、有话说
这道题可以用暴力解法,但我们刷题的目的之一就是能找到“最优解”,这样才有成就感嘛,所以这里用的是kmp,如果有不懂的朋友呢,可以看看卡尔哥的讲解,很nice哦~