LeetCode 27 – Implement strStr()

Posted on January 7, 2014

Last updated on January 7, 2014

Solution to LeetCode Implement strStr() problem.

This is just standard string matching. We can be more fancy and use KMP or Boyer-Moore, but the naive solution passes the test cases.

public String strStr(String haystack, String needle) {
  int N = haystack.length();
  int M = needle.length();
  int i;

  for(i = 0; i <= N-M; i++){
    int j = i;
    int k = 0;
    while(k < M && haystack.charAt(j) == needle.charAt(k)){
      j++;
      k++;
    }
    if(k == M) break;
  }
  if(i > N-M || N < M) return null;
  else return haystack.substring(i);
}
Implement strStr()
Markdown SHA1: b7fe75f7000eda62f5265cce9f2543a1d243141d