Leetcode-Implement strStr()
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char *
or String
, please click the reload button to reset your code definition.
Solution:
1 public class Solution { 2 public int strStr(String haystack, String needle) { 3 if (haystack.length()<needle.length()) return -1; 4 if (needle.length()==0) return 0; 5 int len1 = haystack.length(); 6 int len2 = needle.length(); 7 for (int i=0;i<=len1-len2;i++) 8 if (compare(haystack,i,needle)) 9 return i; 10 11 return -1; 12 } 13 14 public boolean compare(String haystack, int start, String needle){ 15 for (int i=0;i<needle.length();i++){ 16 char c1 = haystack.charAt(start+i); 17 char c2 = needle.charAt(i); 18 if (c1!=c2) return false; 19 } 20 return true; 21 } 22 23 24 }
NOTE: Seems that we can use KMP algorithm. PRACTICE IT!