Title:Implement strStr() 28
Difficulty:Easy
原题leetcode地址:https://leetcode.com/problems/implement-strstr/
1. 暴力法
时间复杂度:O(n^2),一次一层while循环,但是变量i是会不断的回溯的,最大是n^2。
空间复杂度:O(1),没有申请额外的空间。
/**
* 暴力法
* @param haystack
* @param needle
* @return
*/
public static int strStr(String haystack, String needle) {
if (needle.length() == 0) {
return 0;
}
if (haystack.length() < needle.length()) {
return -1;
}
int i = 0;
int j = 0;
while (i < haystack.length() && j < needle.length()) {
if (haystack.charAt(i) == needle.charAt(j)) {
i++;
j++;
}
else {
i = i - j + 1;
j = 0;
}
}
if (j == needle.length()) {
return i - j;
}
else {
return -1;
}
}
2. KMP法
时间复杂度:O(n^2),一次一层while循环,但是变量i是会不断的回溯的,最大是n^2。
空间复杂度:O(m),申请长度为needle字符串的next数组。
/**
* KMP算法:https://www.cnblogs.com/yjiyjige/p/3263858.html
* @param haystack
* @param needle
* @return
*/
public static int strStr1(String haystack, String needle) {
if (needle.length() == 0) {
return 0;
}
if (haystack.length() < needle.length()) {
return -1;
}
int i = 0;
int j = 0;
int next[] = getNext(needle);
while (i < haystack.length() && j < needle.length()) {
if (j == -1 || haystack.charAt(i) == needle.charAt(j)) {
i++;
j++;
}
else {
//i = i - j + 1;
//j = 0;
j = next[j];
}
}
if (j == needle.length()) {
return i - j;
}
else {
return -1;
}
}
/**
* 求next数组
* @param needle
* @return
*/
private static int[] getNext(String needle) {
int next[] = new int[needle.length()];
next[0] = -1;
int j = 0;
int k = -1;
while (j < needle.length() - 1) {
if (k == -1 || needle.charAt(j) == needle.charAt(k)) {
next[++j] = ++k;
}
else {
k = next[k];
}
}
return next;
}