Why my KMP algorithm (13ms) is slow than Brute Force (8ms)


  • 1
    public class Solution {
        public int strStr(String haystack, String needle) {
            if (haystack == null || needle == null || haystack.length() < needle.length()) return -1;
            if (needle.length() == 0) return 0;
            int[] lps = preprocess(needle); 
            int i = 0;
            int j = 0;
            while (i < haystack.length()) {
                if (haystack.charAt(i) == needle.charAt(j)) {
                    if (j == needle.length() - 1) {
                        return i - j;
                    }
                    i++;
                    j++;
                } else {
                    if (j > 0) {
                        j = lps[j - 1];
                    } else {
                        i++;
                    }
                }
            }
            return -1;
        }
        
        public static int[] preprocess(String needle) {
            if (needle == null || needle.length() == 0) return null;
            int[] lps = new int[needle.length()];
            if (needle.length() == 1) {
                return lps;
            }
            int i = 1;
            int j = 0;
            while (i < lps.length) {
                if (needle.charAt(i) == needle.charAt(j)) {
                	lps[i] = j + 1;
                	i++;
                	j++;
                } else {
                	if (j > 0) {
                		j = lps[j - 1];
                	} else {
                		i++;
                	}
                }
            }
            return lps;
        }
    }
    

    Brute Force

    public class Solution {
        public int strStr(String haystack, String needle) {
            if (haystack == null || needle == null || needle.length() < 1) return 0;
            for (int i = 0; i < haystack.length(); i++) {
                if (i + needle.length() > haystack.length()) return -1;
                int m = i;
                for (int j = 0; j < needle.length(); j++) {
                    if (needle.charAt(j) != haystack.charAt(m)) {
                        break;
                    } else {
                        if (j == needle.length() - 1) {
                            return i;
                        }
                        m++;
                    }
                }
            }
            return -1;
        }
    }

  • 1

    same here. :<

    Maybe it's the test case is not well-designed?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.