Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
估计有不少人和我一样对strStr()不熟悉。。。他也不给个例子。也是醉了
public class Solution {
public int strStr(String haystack, String needle) {
int h =0;
int l = needle.length()-1;
if(l<0) return 0;
while(l<haystack.length()){
if(haystack.charAt(h) == needle.charAt(0) && haystack.charAt(l) == needle.charAt(needle.length()-1)){
if(checksub(haystack,h,l,needle)){
return h;
}
}
h++;
l++;
}
return -1;
}
public boolean checksub(String haystack,int start, int end, String needle){
int h =0;
int i =start;
while(i<=end){
if(haystack.charAt(i) != needle.charAt(h)){
return false;
}
i++;
h++;
}
return true;
}
}
微信扫一扫
支付宝扫一扫