LeetCode – 28. Implement strStr()


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;
    }
}

喜欢的话订阅一个呗~第一时间收到文章更新哟~

发表评论

电子邮件地址不会被公开。