您的位置:首页 > 其它

leetcode28: Implement strStr()

2017-01-11 17:08 387 查看
                                                 Implement strStr

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

对haystack进行遍历,比较当前下标下,长度为needle.length()长的字符串是否与needle相等,是则返回,否则,继续下一组比较

package leetcode;

public class leet28 {

public static void main(String[] args) {

leet28 leet = new leet28();
System.out.println(leet.strStr("abcde","db"));
}

public int strStr(String haystack,String needle){

for(int i = 0;i < haystack.length();i++){
int j = 0;
for(j = 0;j < needle.length();j++){
if(haystack.charAt(i+j) != needle.charAt(j)){
break;
}
}
if(j == needle.length()){
return i;
}
}
return -1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: