More:【目錄】LeetCode Java實現html
https://leetcode.com/problems/implement-strstr/java
Implement strStr().api
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.數組
Example 1:oracle
Input: haystack = "hello", needle = "ll" Output: 2
Example 2:post
Input: haystack = "aaaaa", needle = "bba" Output: -1
Clarification:ui
What should we return when needle
is an empty string? This is a great question to ask during an interview.this
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().spa
1.Brute-force solution: Use two pointerscode
2. KMP algorithm
Brute force solution:
public int strStr(String haystack, String needle) { if(haystack==null || needle==null) return -1; for(int i=0;;i++){ for(int j=0;;j++){ if(j==needle.length()) return i; if(i+j==haystack.length()) return -1; if(haystack.charAt(i+j)!=needle.charAt(j)) break; } } }
public int strStr(String haystack, String needle) { if(needle.isEmpty()) return 0; int i=0,j=0; while(i<haystack.length()){ if(haystack.charAt(i)==needle.charAt(j)){ i++; j++; if(j==needle.length()) return i-j; if(i==haystack.length()) return -1; }else{ i=i-j+1; j=0; } } return -1; }
public int strStr(String haystack, String needle) { if(needle.length()==0) return 0; for(int i=0; i<haystack.length()-needle.length()+1; i++){ if(haystack.charAt(i)==needle.charAt(0)){ int j=0; for(; j<needle.length(); j++){ if(haystack.charAt(i+j)!=needle.charAt(j)) break; } if(j==needle.length()) return i; } } return -1; }
KMP:
public int strStr(String haystack, String needle) { if(needle.isEmpty()) return 0; int[] next = getNext(needle); int i=0, j=0; while(i<haystack.length()){ if(j==-1 || haystack.charAt(i)==needle.charAt(j)){ i++; j++; if(j==needle.length()) return i-j; }else{ j=next[j]; } } return -1; } //next[i]數組: // 1. i=0時,next[i]=-1; // 2. 先後綴相等長度爲n時, next[i]=n;(可改進) // 3. 其他:next[i]=0; private static int[] getNext(String str) { if (str == null || str.isEmpty()) return null; int[] next = new int[str.length()]; next[0] = -1; int i = 0, j = -1; //i爲後綴的位置,j爲前綴位置 while (i < str.length() - 1) { //此處範圍注意 if (j == -1 || str.charAt(i) == str.charAt(j)) { i++; j++; //next[i] = j; next[i] = str.charAt(i) == str.charAt(j) ? next[j] : j; //先後綴相等長度爲j } else { j = next[j]; } } return next; }
Brute Force:
Time complexity :
Assume that n = length of haystack and m = length of needle, then the runtime complexity is O(nm).
Space complexity : O(1)
KMP:
Time complexity : O(n)
Space complexity: O(m)
1. It is a great question to ask "What should we return when needle
is an empty string?" during an interview.
More:【目錄】LeetCode Java實現