27. Implement strStr()

mplement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

---

 

public class Solution {
    public String strStr(String haystack, String needle) {
        
        if(haystack == null || needle == null)
            return null;
    
        int len1 = haystack.length();
        int len2 = needle.length();
        
        if(len1 < len2) return null;
        if(len2 == 0)   return haystack; // "" empty string
        
        int i=0;
        while(i < len1){
            int k=i;
            int j=0;
            while(k<len1 && j<len2){
                if(haystack.charAt(k) == needle.charAt(j)){
                    k++;
                    j++;
                }else{
                    break;
                }
            }
            if(j == len2)
                return haystack.substring(i);
            i++;
        }
        
        return null;
    }
}

 

posted @ 2013-09-02 04:51  LEDYC  阅读(165)  评论(0)    收藏  举报