13. strStr

Leave a comment

September 28, 2016 by oneOokay

好吧,重新开始刷一遍。。。

这一题我之前想的略复杂了,想着要存储target与source第一个相等的index,以便之后不等的时候随时取回这个值再+1继续循环。

其实这里就可以直接放置两重循环来实现,第一重来循环source,第二重来循环target,每到一个source的char,尝试着进入内层循环target进行对比。此时外循环的index为source的index,也就有了target 与 source第一个相等的char的index,内层循环的index来对target和source进行判断。此时要注意的是source的index溢出。

public int strStr(String source, String target) {
if (source == null || target == null) {
return -1;
}

if(target.length() == 0) {
return 0;
}

for (int i = 0; i < source.length() – target.length() + 1; i ++) {
int j = 0;
for (j = 0; j < target.length(); j ++) {
if (source.charAt(i + j) == target.charAt(j)) {
continue;
}else {
break;
}
}
if (j == target.length()){
return i;
}
}
return -1;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: