Implement strStr()

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

遍历算法

 1 public class Solution {
 2     public String strStr(String haystack, String needle) {
 3      
 4         if(haystack == null || needle == null) 
 5             return null;
 6         if(needle.length() == 0)
 7             return haystack;
 8         if(haystack.length() == 0)
 9             return null;
10             
11         int needleLen = needle.length();
12         int haystackLen = haystack.length();
13      
14         for (int i = 0; i < haystackLen; i++) {
15             // make sure in boundary of needle
16             if (haystackLen - i + 1 < needleLen)
17                 return null;
18      
19             int k = i;
20             int j = 0;
21      
22             while (j < needleLen && k < haystackLen && needle.charAt(j) == haystack.charAt(k)) {
23                 j++;
24                 k++;
25                 if (j == needleLen)
26                     return haystack.substring(i);
27             }
28      
29         }
30      
31         return null;
32     }
33 }

 

 

 

KMP 算法

public class Solution {
    public String strStr(String haystack, String needle) {
        if(haystack == null || needle == null) 
            return null;
        if(needle.length() == 0)
            return haystack;
        if(haystack.length() == 0)
            return null;
            
            char[] hay = haystack.toCharArray();
            char[] nee = needle.toCharArray();
            int Hlen = hay.length;
            int Nlen = nee.length;
            String str = match(hay, nee, Hlen, Nlen);
            return str;
    }
    
    public String match (char[] hay, char[] nee, int Hlen, int Nlen){
        int i = 0; int j=0;
        int[] next = getNext(nee, Nlen);
        while(i<Hlen) {
            if( j == -1 || hay[i] == nee[j]) {
                i++;
                j++;
            }else{
                j =next[j];
            }
            if(j == Nlen){
                String temp = String.valueOf(hay);
                String result = temp.substring(i-Nlen);
                return result;
            }
        }
        return null;
    }
    
    public int[] getNext(char[] nee, int Nlen){
        int[] next = new int[Nlen];
        int i =0; int k = -1;
        next[0] = -1;
        while(i< Nlen-1){
            if(k == -1 || nee[i] == nee[k]){
                i++;
                k++;
                next[i] =k;
            }else{
                k =next[k];
            }
        }
        return next;
    }
    
}

 

posted @ 2014-01-25 17:31  Razer.Lu  阅读(189)  评论(0编辑  收藏  举报