String类中的indexOf方法为什么不采用KPM算法进行字符串的匹配查找啊?

chenyuanbin26 2011-10-15 07:51:48
前几天看了下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;
}
...全文
550 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
caishenfans 2011-10-17
  • 打赏
  • 举报
回复
KMP对特殊的字符串比较好用 就是自身带有很多重复子串的那种
而且在字符串不长的情况下 KMP耗时更多 (自己测试一下就知道了)
chenyuanbin26 2011-10-17
  • 打赏
  • 举报
回复
多谢提醒,我去测试下看看。KMP算法有点空间换时间的意思,不晓得设计者是不是有考虑空间的问题。

[Quote=引用 4 楼 caishenfans 的回复:]

KMP对特殊的字符串比较好用 就是自身带有很多重复子串的那种
而且在字符串不长的情况下 KMP耗时更多 (自己测试一下就知道了)
[/Quote]
chenchenyangll 2011-10-16
  • 打赏
  • 举报
回复
究竟标准说法是KMP 还是 KPM 查一下两个都对。。。
巽谷雨 2011-10-16
  • 打赏
  • 举报
回复
等待高手解决
chenyuanbin26 2011-10-16
  • 打赏
  • 举报
回复
应该是KMP算法,拼写错误,请见谅

[Quote=引用 2 楼 chenchenyangll 的回复:]

究竟标准说法是KMP 还是 KPM 查一下两个都对。。。
[/Quote]

62,629

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧