题目:
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 classSolution {2 public intstrStr(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 returni;17 }18 }19
20 return -1;21 }22 }
本题还可以采用KMP算法,这篇帖子说的很详细。
注意在求next数组时,while loop的条件是q
Time Complexity: O(m+n). m = haystack.length(), n = needle.length(). Space: O(n)
AC Java:
1 public classSolution {2 public intstrStr(String haystack, String needle) {3 if(haystack == null || needle == null || haystack.length()
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
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 }
参见如下两篇文章: