Question

link

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

Stats

Frequency 5
Diffficulty 4
Adjusted Difficulty 4
Time to use ----------

Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)

Analysis

There are 2 ways to solve this problem.

  1. Most common way is using 2 nested loop

  2. Also can be solved by KPM algorithm

Solution

Standard solution is posted below. Read this post for more.

As for KMP algo, I have to admit I am not able to do it. Plz refer to this blog and this blog for more!

My code

public class Solution {
    public int strStr(String haystack, String needle) {
        if (haystack == null || needle == null) {
            return -1;
        } else if (haystack.length() < needle.length()) {
            return -1;
        } else if (haystack.length() == 0 && needle.length() == 0) {
            return 0;
        }
        for (int i = 0; i <= haystack.length() - needle.length(); i++) {
            int j;
            // try to match part of haystack (starting from i) to needle
            for (j = 0; j < needle.length(); j++) {
                if (haystack.charAt(i + j) != needle.charAt(j)) {
                    break;
                }
            }
            // if part of haystack (starting from i) matches needle
            if (j == needle.length()) {
                return i;
            }
            // if not match, proceed to next loop
        }
        return -1;
    }
}