实现 strStr() 函数
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例1:
示例2:
提示:
Java解法
package sj.shimmer.algorithm.ten_2;
/**
* Created by SJ on 2021/2/11.
*/
class D18 {
public static void main(String[] args) {
// System.out.println(strStr("hello","ll"));
// System.out.println(strStr("aaabb","bb"));
// System.out.println(strStr("aaaaa","bba"));
// System.out.println(strStr("",""));
System.out.println(strStr("mississippi", "issip"));
}
public static int strStr(String haystack, String needle) {
if (haystack == null) {
return -1;
}
if (needle==null) {
return -1;
}
if ("".equals(needle)) {
return 0;
}
int slow = 0;
int fast = 0;
while (slow<haystack.length()){
if (slow>haystack.length()-needle.length()) {
break;
}
for (int i = 0; i < needle.length(); i++) {
if (fast<haystack.length()&&haystack.charAt(fast)==needle.charAt(i)) {
if (i==needle.length()-1) {
return slow;
}
fast++;
}else {
break;
}
}
slow++;
fast = slow;
}
return -1;
}
}
官方解
https://leetcode-cn.com/problems/implement-strstr/solution/shi-xian-strstr-by-leetcode/
-
子串逐一比较 - 线性时间复杂度
- 时间复杂度:O((N - L)L)
- 空间复杂度:O(1)
-
双指针 - 线性时间复杂度
- 时间复杂度:O((N - L)L), 最优时间复杂度为 O(N)O(N)
- 空间复杂度:O(1)
-
其他优化
- 大佬的KMP优化思想:needle中不存在的子串时实际上是可以不用回退那么多的,后续题刷多了总结下思想研究下