前几天看了下java中String类中的源代码,String类中有个static的indexOf方法,用于查找子串首次出现的位置,代码贴在下面。如果我没有看错的话,源代码使用暴力的遍历查找,时间复杂度应该是O(n*m)。我在想,为什么java的实现不采用KPM算法来进行字符串的匹配查找呢?KPM算法的时间复杂度不是O(n),这样效率不是更好吗?希望哪位大侠指定一二,可能是我哪个地方理解不对?static int indexOf(char[] source, int sourceOffset, int sourceCount,
                       char[] target, int targetOffset, int targetCount,
                       int fromIndex) {
if (fromIndex >= sourceCount) {
            return (targetCount == 0 ? sourceCount : -1);
}
     if (fromIndex < 0) {
         fromIndex = 0;
     }
if (targetCount == 0) {
    return fromIndex;
}        char first  = target[targetOffset];
        int max = sourceOffset + (sourceCount - targetCount);        for (int i = sourceOffset + fromIndex; i <= max; i++) {
            /* Look for first character. */
            if (source[i] != first) {
                while (++i <= max && source[i] != first);
            }            /* Found first character, now look at the rest of v2 */
            if (i <= max) {
                int j = i + 1;
                int end = j + targetCount - 1;
                for (int k = targetOffset + 1; j < end && source[j] ==
                         target[k]; j++, k++);                if (j == end) {
                    /* Found whole string. */
                    return i - sourceOffset;
                }
            }
        }
        return -1;
    }

解决方案 »

  1.   

    究竟标准说法是KMP 还是 KPM  查一下两个都对
      

  2.   

    应该是KMP算法,拼写错误,请见谅
      

  3.   

    KMP对特殊的字符串比较好用 就是自身带有很多重复子串的那种
    而且在字符串不长的情况下 KMP耗时更多 (自己测试一下就知道了)
      

  4.   

    多谢提醒,我去测试下看看。KMP算法有点空间换时间的意思,不晓得设计者是不是有考虑空间的问题。