Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Solution:
Method 1: Brute Force
An optimized brute force implementation.
The time complexity is O(n2).
Code:
public class Solution { public int strStr(String haystack, String needle) { for (int i = 0; i < haystack.length() - needle.length() + 1; i++) { int j = 0; for (; j < needle.length(); j++) { if (haystack.charAt(i + j) != needle.charAt(j)) { break; } } if (j == needle.length()) { return i; } } return -1; } }
Method 2 : Booye-Moore
The idea is to pre-process a table that when we do the compare of two strings, we know how many steps to skip and continue comparing.
The best time complexity is O(m / n) and worst cast time complexity is O(mn).
The space complexity is O(1).
Code:
public class Solution { public int strStr(String haystack, String needle) { int m = haystack.length(); int n = needle.length(); int[] right = new int[256]; Arrays.fill(right, -1); for (int j = 0; j < n; j++) { right[needle.charAt(j)] = j; } int skip = 0; for (int i = 0; i < m - n + 1; i++) { skip = 0; for (int j = n - 1; j >= 0; j--) { if (haystack.charAt(i + j) != needle.charAt(j)) { skip = Math.max(1, right[haystack.charAt(i + j)]); break; } } if (skip == 0) { return i; } } return -1; } }