1.3 strStr

Definition

Return the location of target string in source string.

Logical Steps

  1. Outer loop through source string
  2. Inner loop through target
  3. If source[i] not equal to target[j], skip
  4. When target[j] at last element and skip, it will skip to source[i+1] instead of returning the result

Code Template

for (i through source) {
    for (j through target) {
        // When target[j] at last element and skip, 
        // it will skip to source[i+1] instead of returning the result
        if (target.charAt(i) != source.charAt(j))
            continue;

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

Common Mistakes

  1. Return i - target.length() instead of i - target.length() + 1 (i index is 0 based, where target.length() is 1 based, need to +1 to fix that)