Description
For a given source string and a target string, you should output the first index(from 0) of target string in source string.
If target does not exist in source, just return -1.
Analysis
难
2h of thinking
Code
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;
}
if (target == "") {
return 0;
}
if (source == "") {
return -1;
}
int start = 0;
// 如果剩下的字母不够needle长度就停止遍历
while(start <= source.length() - target.length()){
int i1 = start, i2 = 0;
while(i2 < target.length() && source.charAt(i1) == target.charAt(i2)){
i1++;
i2++;
}
if(i2 == target.length()) return start;
start++;
}
return -1;
}
}
网友评论