1.3 strStr
Definition
Return the location of target string in source string.
Logical Steps
- Outer loop through source string
- Inner loop through target
- If source[i] not equal to target[j], skip
- 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
- 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)