Implement strStr() (E)
题目
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().
题意
找到匹配的字串。
思路
暴力法(O(MN))。
KMP。
代码实现
Java
暴力
class Solution {
public int strStr(String haystack, String needle) {
if (needle.equals("")) {
return 0;
}
for (int i = 0; i < haystack.length(); i++) {
if (haystack.length() - i < needle.length()) {
break;
}
if (haystack.charAt(i) == needle.charAt(0)) {
int j = i, k = 0;
while (k < needle.length()) {
if (haystack.charAt(j) != needle.charAt(k)) {
break;
}
j++;
k++;
}
if (k == needle.length()) {
return i;
}
}
}
return -1;
}
}
KMP
class Solution {
public int strStr(String haystack, String needle) {
if (needle.length() == 0) {
return 0;
}
int[] next = new int[needle.length()];
int i = 1, p = 0;
while (i < needle.length()) {
if (needle.charAt(i) == needle.charAt(p)) {
next[i++] = ++p;
} else if (p > 0) {
p = next[p - 1];
} else {
next[i++] = 0;
}
}
i = 0;
p = 0;
while (i < haystack.length()) {
if (haystack.charAt(i) == needle.charAt(p)) {
i++;
p++;
if (p == needle.length()) {
return i - p;
}
} else if (p > 0) {
p = next[p - 1];
} else {
i++;
}
}
return -1;
}
}
JavaScript
暴力
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function (haystack, needle) {
if (needle.length === 0) {
return 0
}
for (let i = 0; i < haystack.length; i++) {
if (haystack.length - i < needle.length) {
break
}
let isMatch = true
for (let j = 0; j < needle.length; j++) {
if (needle[j] !== haystack[i + j]) {
isMatch = false
break
}
}
if (isMatch) {
return i
}
}
return -1
}
KMP
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function (haystack, needle) {
if (needle.length === 0) {
return 0
}
let next = new Array(needle.length).fill(0)
let p = 0, q = 1
while (q < needle.length) {
if (needle[q] === needle[p]) {
next[q++] = ++p
} else if (p > 0) {
p = next[p - 1]
} else {
next[q++] = 0
}
}
p = 0, q = 0
while (q < haystack.length) {
if (needle[p] === haystack[q]) {
p++
q++
if (p === needle.length) {
return q - needle.length
}
} else if (p > 0) {
p = next[p - 1]
} else {
q++
}
}
return -1
}