1 public class Solution { 2 public String strStr(String haystack, String needle) { 3 // IMPORTANT: Please reset any member data you declared, as 4 // the same Solution instance will be reused for each test case. 5 int needleLen = needle.length(); 6 int haystackLen = haystack.length(); 7 if (needleLen > haystackLen) 8 return null; 9 10 if (needleLen == 0) 11 return haystack; 12 13 int i = 0; 14 for (; i < haystackLen - needleLen + 1;) { 15 int j = 0; 16 for (; j < needleLen;) { 17 if (needle.charAt(j) == haystack.charAt(i)) { 18 i++; 19 j++; 20 } else { 21 break; 22 } 23 } 24 if (j == needleLen) { 25 i = i - j; 26 return haystack.substring(i, haystackLen); 27 } else { 28 i = i - j + 1; 29 } 30 31 } 32 33 return null; 34 } 35 }
O(m*n) level 1
KMP algorithm level 5