028.Implement strStr() Posted on 2017-09-16 | In LeetCode Solution 1: accepted 18msBrute force. 12345678910111213141516171819202122public int strStr(String haystack, String needle) { if (haystack == null || needle == null) { return -1; } if (needle.length() == 0) { return 0; } int j = 0; for (int i = 0; i < haystack.length() - needle.length() + 1; i++) { for (j = 0; j < needle.length(); j++) { if (haystack.charAt(i + j) != needle.charAt(j)) { break; } } if (j == needle.length()) { return i; } } return -1;} Solution 2: accepted 58%KMP. 1234567891011121314151617181920212223public class Solution { public int strStr(String haystack, String needle) { int hayLen = haystack.length(); int nedLen = needle.length(); if (nedLen == 0) { return 0; } for(int i = 0; i < hayLen - nedLen + 1; i++) { int hay = i; int ned = 0; while (haystack.charAt(hay) == needle.charAt(ned)) { hay++; ned++; if (ned == nedLen) return i; continue; } } return -1; }} Neat but slower (28%) KMP. 1234567891011public class Solution { public int strStr(String haystack, String needle) { 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; } } }}