Implement strStr()

来源:互联网 发布:单片机应用技术 编辑:程序博客网 时间:2024/05/01 07:02

Question:

Implement strStr().

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


//********** Hints ************

KMP算法详解: http://www.cnblogs.com/yjiyjige/p/3263858.html

//*****************************


Solution:

public class Solution {
    public String strStr(String haystack, String needle) {
        char[] n = needle.toCharArray();
        char[] h = haystack.toCharArray();
        
        
        
        assert(haystack!=null && needle!=null);
        if(needle.length()==0) return haystack;
        
        int[] next = getNext(needle);
        
        int i = 0;
        int j = 0;
        
        while(i < haystack.length() && j < needle.length()){
            if(j == -1 || n[j] == h[i]){
                j++;
                i++;
            }
            else{
                j = next[j];
            }
        }
        
        if(j == needle.length()){
            return haystack.substring(i-j);
        }
        
        else
            return null;
    }
    
    public int[] getNext(String s){
        char[] target = s.toCharArray();
        int[] next = new int[s.length()];
        
        next[0] = -1;
        int j =0;
        int k = -1;
        
        while(j < s.length() -1){
            if(k== -1 || target[j] == target[k]){
                next[++j] = ++k;
            }
            else{
                k = next[k];
            }
        }
        
        return next;
    }
}


0 0
原创粉丝点击