java的indexOf实现了什么类型的算法

时间:2014-12-30 13:25:20

标签: java algorithm

我需要弄清楚indexOf() java.lang.String方法在其源代码中实现的算法类型: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算法,因为没有强调寻找模式不匹配。

1 个答案:

答案 0 :(得分:1)

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

更多信息herehere