原题链接在这里:https://leetcode.com/problems/implement-strstr/
题目:
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().
题解:
Brute force的算法是从haystack头开始走,每次取后面长度与needle长度相等的substring, 看这个substring与needle是否相同即可.
If needle is empty, return 0.
Note: s.substring(i), i could be s.length(), and return "". Thus here, it is allowed to use i <= m - n.
Time Complexity: O(m*n), m = haystack.length(), n = needle.length().
Space: O(1).
AC Java:
1 class Solution { 2 public int strStr(String haystack, String needle) { 3 if(haystack == null || needle == null){ 4 return -1; 5 } 6 7 if(needle.length() == 0){ 8 return 0; 9 } 10 11 int m = haystack.length(); 12 int n = needle.length(); 13 14 for(int i = 0; i <= m - n; i++){ 15 if(haystack.substring(i, i + n).equals(needle)){ 16 return i; 17 } 18 } 19 20 return -1; 21 } 22 }
本题还可以采用KMP算法,这篇帖子说的很详细。
注意在求next数组时,while loop的条件是q<len-1, 因为下面还用到q++后的next[q]. next array的含义是到当前char的前一位的最大公共前缀后缀.
Time Complexity: O(m+n). m = haystack.length(), n = needle.length(). Space: O(n)
AC Java:
1 public class Solution { 2 public int strStr(String haystack, String needle) { 3 if(haystack == null || needle == null || haystack.length() < needle.length()){ 4 return -1; 5 } 6 7 if(needle.length() == 0){ 8 return 0; 9 } 10 11 int i = 0; 12 int j = 0; 13 int len1 = haystack.length(); 14 int len2 = needle.length(); 15 int [] next = new int[len2]; 16 getNext(needle, next); 17 while(i<len1 && j<len2){ 18 if(j == -1 || haystack.charAt(i) == needle.charAt(j)){ 19 i++; 20 j++; 21 }else{ 22 j = next[j]; 23 } 24 } 25 26 if(j == len2){ 27 return i-j; 28 }else{ 29 return -1; 30 } 31 } 32 33 private void getNext(String s, int [] next){ 34 int len = s.length(); 35 next[0] = -1; 36 int p = -1; 37 int q = 0; 38 while(q < len-1){ 39 //s.charAt(p)表示前缀. s.charAt(q)表示后缀 40 if(p == -1 || s.charAt(p) == s.charAt(q)){ 41 p++; 42 q++; 43 next[q] = p; 44 }else{ 45 p = next[p]; 46 } 47 } 48 } 49 }
参见如下两篇文章: