您的位置:首页 > 其它

28. Implement strStr()

2016-02-24 09:04 218 查看
最简单的方法,暴力找

public int strStr(String haystack, String needle) {
if(needle == null || needle.length() == 0) {
return 0;
}
if(haystack.length() < needle.length()) {
return -1;
}
for(int i = 0; i <= haystack.length()-needle.length(); i++) {//需要<=
int j = 0;
while(j < needle.length()) {
if(haystack.charAt(i+j) == needle.charAt(j)) {
j++;
} else {
break;
}
if(j == needle.length()) {
return i;
}
}
}
return -1;
}


bug记录:

1.第16行,错写成j == needle.length()-1,但是其实如果匹配,那么12行已经进行过j++此时应该是j == needle.length()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: