Thinking process

Empty string? occurrence multiple times? what if it's not there?

Time Complexity

O (n^2)

class Solution {
    /**
     * Returns a index to the first occurrence of target in source,
     * or -1  if target is not part of source.
     * @param source string to be scanned.
     * @param target string containing the sequence of characters to match.
     */
    public int strStr(String source, String target) {
        if (source == null || target == null || source.length() < target.length()) return -1;
        if (target.length() == 0) return 0;

        for (int i = 0; i < source.length(); ++i) {
            int index = i;
            for (int j = 0; j < target.length(); ++j) {
                if (source.charAt(index) != target.charAt(j)) {
                    break;
                } else {
                    if (index < source.length() - 1) index++;
                    if (j == target.length() - 1) {
                        return i;
                    }
                }
            }
        }

        return -1;
    }
}

Improve

remove variable index

Mistakes

  1. i + j may be larger than the length
  2. don't need to check target is empty
class Solution {
    /**
     * Returns a index to the first occurrence of target in source,
     * or -1  if target is not part of source.
     * @param source string to be scanned.
     * @param target string containing the sequence of characters to match.
     */
    public int strStr(String source, String target) {
        if (source == null || target == null || source.length() < target.length()) return -1;
        int i = 0, j = 0;
        for (i = 0; i < source.length() - target.length() + 1; ++i) {
            for (j = 0; j < target.length(); ++j) {
                if (source.charAt(i + j) != target.charAt(j)) {
                    break;
                } 
            }

            if (j == target.length()) return i;
        }

        return -1;
    }
}

results matching ""

    No results matching ""