KMP算法

jopen 9年前發布 | 2K 次閱讀 C/C++ 算法

KMP算法 
【題目】 
給定兩個字符串str和match,長度分別為N和M。實現一個算法,如果字符串str中含有字串match,則返回match在str中的開始位置,不含有則返回-1。 
【舉例】 
str=“acbc”,match=“bc”。返回2。 
str=“acbc”,match=“bcc”。返回-1。 
【要求】 

如果match的長度大于str長度(M>N),str必然不會含有match,可直接返回-1。但如果N>=M,要求算法復雜度O(N)。 

   public int getIndexOf(String s, String m) { 
        if (s == null || m == null || m.length() < 1 || s.length() < m.length()) { 
        return -1; 
        } 
        char[] ss = s.toCharArray(); 
        char[] ms = m.toCharArray(); 
        int si = 0; 
        int mi = 0; 
        int[] next = getNextArray(ms); 
        while (si < ss.length && mi < ms.length) { 
        if (ss[si] == ms[mi]) { 
            si++; 
            mi++; 
        } else if (next[mi] == -1) { 
            si++; 
        } else { 
            mi = next[mi]; 
        } 
        } 
        return mi == ms.length ? si - mi : -1; 
    } 


    public int[] getNextArray(char[] ms) { 
        if (ms.length == 1) { 
            return new int[] { -1 }; 
        } 
        int[] next = new int[ms.length]; 
        next[0] = -1; 
        next[1] = 0; 
        int pos = 2; 
        int cn = 0; 
        while (pos < next.length) { 
            if (ms[pos - 1] == ms[cn]) { 
                next[pos++] = ++cn; 
            } else if (cn > 0) { 
                cn = next[cn]; 
            } else { 
                next[pos++] = 0; 
            } 
        } 
        return next; 
    }

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!