[Leetcode] implement strStr()

implement strStr()

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

brute force

don’t overlook this simple question. be careful on the details.


edgecase:

haystack == null?  false

needle == null?      false

needle isEmpty()??  0

 

    public int strStr(String haystack, String needle) {
        if(haystack == null || needle == null) return -1;
        if(needle.length() == 0) return 0;
        //haystack "aaa"
        //needle "a"
        for(int i = 0; i < haystack.length()-needle.length()+1; i++){
    
            if(haystack.charAt(i) == needle.charAt(0)){
                int j = 1;
                for(; j < needle.length(); j++){
                    if(haystack.charAt(i+j) != needle.charAt(j)){
                        break;
                    }
                }
            
                if(j == needle.length()) return i;
            }
        }
        return -1;
        
    }

 

posted @ 2015-09-30 08:41  momocoisapeach  阅读(123)  评论(0编辑  收藏  举报