LeetCode 28 - Implement strStr()

Implement strStr().

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

Solution 1:

Naive method.

public int strStr(String a, String p) {
    int i, j, n = a.length(), m = p.length();
    for (i = 0, j = 0; j < m && i < n; i++, j++) {
        if (a.charAt(i) != p.charAt(j)) { 
            i -= j; 
            j = -1; 
        }
    }
    if (j == m) return i-m; 
    return -1;
}

 

Solution 2:

KMP method.

// KMP matching
public int strStr(String a, String p) {
    if(a == p || "".equals(p)) return 0;
    int i, j, n = a.length(), m = p.length();
    int[] next = preprocess(p);
    for (i = 0, j = 0; j < m && i < n; i++, j++) {
        while (j>=0 && a.charAt(i) != p.charAt(j)) { 
            j = next[j];
        }
    }
    if (j == m) return i-m;
    return -1; 
}
// KMP partial match table
private int[] preprocess(String pattern) {
    char[] p = pattern.toCharArray();
    int i = 0, j = -1, m=p.length;
    int[] b = new int[m+1];
    b[0] = j;
    while(i<m) {
        while(j>=0 && p[i] != p[j]) {
            j = b[j];
        }
        b[++i] = ++j;
    }
    return b;
}

After a shift of the pattern, the naive algorithm has forgotten all information about previously matched symbols. So it is possible that it re-compares a text symbol with different pattern symbols again and again. This leads to its worst case complexity of Θ(nm) (n: length of the text, m: length of the pattern).

The algorithm of Knuth, Morris and Pratt makes use of the information gained by previous symbol comparisons. It never re-compares a text symbol that has matched a pattern symbol. As a result, the complexity of the searching phase of the Knuth-Morris-Pratt algorithm is in O(n).

However, a preprocessing of the pattern is necessary in order to analyze its structure. The preprocessing phase has a complexity of O(m). Since mn, the overall complexity of the Knuth-Morris-Pratt algorithm is in O(n).

 

Reference:

http://www.inf.fh-flensburg.de/lang/algorithmen/pattern/kmpen.htm 

你可能感兴趣的:(LeetCode 28 - Implement strStr())