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().
解法一:找不到工作的解法
class Solution {
public int strStr(String haystack, String needle) {
return haystack.indexOf(needle);
}
}
解法二:暴力
class Solution {
public int strStr(String haystack, String needle) {
if(needle.length()==0) return 0;
if(haystack.length()<needle.length()) return -1;
for(int i=0;i<haystack.length();i++){
int k = i;
for(int j=0;needle.length()+i<=haystack.length()&&j<needle.length();j++){
if(haystack.charAt(k)!=needle.charAt(j)){
break;
}else{
k++;
if(j==needle.length()-1) return i;
}
}
}
return -1;
}
}
解法三:使用next的KMP算法
思路: 在Leetcode上运行感觉效率并不高
class Solution {
public int strStr(String haystack, String needle) {
if(needle.length()==0) return 0;
if(haystack.length()<needle.length()) return -1;
int[] next = creatNext(needle);
int i=0,j=0;
while(i<haystack.length()&&j<needle.length()){
if(j==-1||haystack.charAt(i)==needle.charAt(j)){
i++;
j++;
}else{
j = next[j];
}
}
if(j==needle.length()) return i-needle.length();
return -1;
}
public int[] creatNext(String needle){
int len = needle.length();
int[] next = new int[len];
next[0] = -1;
int j=-1;
int i=0;
while(i<len-1){
if(j==-1||needle.charAt(i)==needle.charAt(j)){
j++;
i++;
next[i] = j;
}else{
j = next[j];
}
}
return next;
}
}
解法三:另一种KMP
class Solution {
public int strStr(String haystack, String needle) {
if(needle==null||needle.length()==0) return 0;
int l1 = haystack.length();
int l2 = needle.length();
if(l1<l2) return -1;
int[][] dp = createDp(needle);
int j = 0;
for(int i=0;i<l1;i++){
j = dp[j][haystack.charAt(i)];
if(j==l2){
return i-l2+1;
}
}
return -1;
}
public int[][] createDp(String needle){
int len = needle.length();
int[][] dp = new int[len][256];
dp[0][needle.charAt(0)] = 1;
int x = 0;
for(int j=1;j<len;j++){
for(int i=0;i<256;i++){
if(needle.charAt(j)==i){
dp[j][i] = j+1;
}else{
dp[j][i] = dp[x][i];
}
}
x = dp[x][needle.charAt(j)];
}
return dp;
}
}