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;
}
}
13.StrStr
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 小学语文修改病句的方法 修改病句是小学语文考试中常见的题型,在修改病句之前,我们应该清晰的了解有哪些病句现象,下面...
- 上图是从时间法则官网下载的资料图片。 是一条波符的代表图形。 一个点代表1,一条横线代表5,然后你就会知道点和横线...
- 最近我又看了一部很棒的美剧,改编自Jay Asher的同名小说《13 Reasons Why》。 由Netflix...