【问题标题】:What type of algorithm does java's indexOf implementjava的indexOf实现的是什么类型的算法
【发布时间】:2014-12-30 13:25:20
【问题描述】:

我需要弄清楚java.lang.String的indexOf()方法在他们的源代码中实现了什么样的算法:http://grepcode.com/file_/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java/?v=source

public int indexOf(int ch, int fromIndex) {
        int max = offset + count;
        char v[] = value;

        if (fromIndex < 0) {
            fromIndex = 0;
        } else if (fromIndex >= count) {
            // Note: fromIndex might be near -1>>>1.
            return -1;
        }

        int i = offset + fromIndex;
        if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
            // handle most cases here (ch is a BMP code point or a
            // negative value (invalid code point))
            for (; i < max ; i++) {
                if (v[i] == ch) {
                    return i - offset;
                }
            }
            return -1;
        }

        if (ch <= Character.MAX_CODE_POINT) {
            // handle supplementary characters here
            char[] surrogates = Character.toChars(ch);
            for (; i < max; i++) {
                if (v[i] == surrogates[0]) {
                    if (i + 1 == max) {
                        break;
                    }
                    if (v[i+1] == surrogates[1]) {
                        return i - offset;
                    }
                }
            }
        }
        return -1;
    }

据我所知,这应该是一种蛮力算法,而不是 Knuth-Morris-Pratt 算法,因为它不强调寻找模式不匹配。

【问题讨论】:

  • 此函数搜索单个字符。当然,您看不到任何 KMP 代码。你为什么不看indexOf(String)?
  • 好吧,我会说“搜索”,但 @MarkoTopolnik 说的是什么。
  • 是什么让你认为它可能不是蛮力?
  • 看重载方法可能更有意义,实际上搜索字符串的索引。但是,为了省去您的麻烦,它并不比单字符搜索更复杂。
  • 我认为 java 的整个子字符串搜索让我失望,考虑到正在搜索字符数组,而其他算法搜索整个模式。我想我也混淆了源中评论为 KMP 的 BMP

标签: java algorithm


【解决方案1】:

ode 使用 蛮力算法 在给定字符串中查找 substring。也就是说,该方法在 O(mn) 中运行,其中m and n are the length of the source and target strings。

更多信息here和here

【讨论】:

    猜你喜欢
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-30
    • 1970-01-01
    相关资源
    最近更新 更多