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;
}
}
This site Original article All followed" Attribution—NonCommercial—ShareAlike 4.0 (CC BY-NC-SA 4.0) ”。 Please keep the following marks for sharing and interpretation:
Original author: Jake Tao Source: 「LeetCode – 28. Implement strStr()」
Post a reply