28 Implement strSTR

Question:

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Lesson Learned:

  • in the string, I use == to compare again !!!!!! Oh NO!!!
  • I use j = 1 first, but that cause a problem: if just 1 letter, the loop cannot be entered.
  • while running the program in your head, use the code, not your thought!
  • Should always consider "" in a string. You should think: if the string is "", we will not reach charAt(0).

My first attempt:

public class Solution {
    public int strStr(String haystack, String needle) {
        // in the string, I use == to compare again !!!!!! Oh NO!!!
        if (haystack == null || needle == null || (haystack.equals("") && !needle.equals(""))) {
            return -1;
        }
        if (needle.equals("")) {
            return 0;
        }
        // I forgot needle = ""
        int hl = haystack.length();
        int nl = needle.length();
        char c = needle.charAt(0);
        for (int i = 0; i < hl - nl + 1; i++) {
            if (haystack.charAt(i) == c) {
                // I use j = 1 first, but that cause a problem: if just 1 letter, the loop cannot be entered.
                for (int j = 0; j < nl; j++) {
                    // while running the program in your head, use the code, not your thought!
                    if (haystack.charAt(i+j) != needle.charAt(j)) {
                        break;
                    }
                    if (j == nl - 1) {
                        return i;
                    }
                }
            }
        }
        return -1;
    }
}

updated:(12.18.15)

public class Solution {
    public int strStr(String str, String target) {
        if (str == null || target.length() == 0) {
            return 0;
        }
        // Should always consider "" in a string.

        for (int i = 0; i < str.length() - target.length() + 1; i++) {
            // In string, you should think: if the string is "", we will not reach charAt(0).
            if (str.charAt(i) == target.charAt(0)) {
                for (int j = 0; j < target.length(); j++) {
                    if (str.charAt(i + j) != target.charAt(j)) {
                        break;
                    }
                    if (j == target.length() - 1) {
                        return i;
                    }
                }
            }
        }
        return -1;
    }
}