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) {
//write your code here
if (source == null || target == null) return -1;
int sourceLength = source.length();
int targetLength = target.length();
if (sourceLength - targetLength < 0) return -1;
for (int i = 0; i < sourceLength - targetLength + 1; i++) {
int sourceCurrentPosition = i;
int targetCurrentPosition = 0;
for (int j = 0; j < targetLength; j++) {
if (source.charAt(sourceCurrentPosition) == target.charAt(targetCurrentPosition)) {
sourceCurrentPosition++;
targetCurrentPosition++;
}
}
if (targetCurrentPosition == targetLength) return i;
}
return -1;
}
}
网友评论