欢迎访问宙启技术站
智能推送

Java函数实现字符串匹配算法:如何在字符串中查找指定的文本?

发布时间:2023-06-19 20:32:44

字符串匹配算法是计算机科学中的常见问题,指的是查找文本中的指定模式。这在信息处理和搜索引擎中应用广泛。在Java中,有多种方法可供实现字符串匹配算法。

1. Brute-Force算法

Brute-Force算法是最简单、最基本的字符串匹配算法,在文本串中顺序地比较每个字符是否匹配。它的时间复杂度为O(m*n),其中m为模式串的长度,n为文本串的长度。以下代码实现了Brute-Force算法:

public static int bruteForce(String s, String t) {

    int i = 0; //文本串下标

    int j = 0; //模式串下标

    int sLen = s.length();

    int tLen = t.length();

    while (i < sLen && j < tLen) {

        if (s.charAt(i) == t.charAt(j)) { //匹配成功

            i++;

            j++;

        } else { //匹配失败,回溯

            i = i - j + 1;

            j = 0;

        }

    }

    if (j == tLen) { //匹配成功

        return i - j;

    } else { //匹配失败

        return -1;

    }

}

2. KMP算法

KMP算法(Knuth-Morris-Pratt算法)是一种更高效的字符串匹配算法,它通过预处理模式串来避免重复比较。时间复杂度为O(m+n)。以下代码实现了KMP算法:

public static int kmp(String s, String t) {

    int i = 0; //文本串下标

    int j = 0; //模式串下标

    int sLen = s.length();

    int tLen = t.length();

    int[] next = getNext(t); //预处理next数组

    while (i < sLen && j < tLen) {

        if (j == -1 || s.charAt(i) == t.charAt(j)) {

            i++;

            j++;

        } else { //失配,回溯

            j = next[j];

        }

    }

    if (j == tLen) { //匹配成功

        return i - j;

    } else { //匹配失败

        return -1;

    }

}

private static int[] getNext(String t) {

    int[] next = new int[t.length()];

    next[0] = -1;

    int i = 0;

    int j = -1;

    while (i < t.length() - 1) {

        if (j == -1 || t.charAt(i) == t.charAt(j)) {

            i++;

            j++;

            next[i] = j;

        } else {

            j = next[j];

        }

    }

    return next;

}

3. Boyer-Moore算法

Boyer-Moore算法是一种启发式的字符串匹配算法,其思想是从模式串的结尾开始比较字符,当发现不匹配时,根据不同情况选择跳过一段字符或移动模式串。时间复杂度为O(m+n)。以下代码实现了Boyer-Moore算法:

public static int boyerMoore(String s, String t) {

    int i = t.length() - 1; //模式串下标

    int j = t.length() - 1; //文本串下标

    int sLen = s.length();

    int tLen = t.length();

    while (i < sLen && j >= 0) {

        if (s.charAt(i) == t.charAt(j)) { //匹配成功

            i--;

            j--;

        } else { //匹配失败

            int k = j - getLast(t.substring(0, j), s.charAt(i)); //计算跳过的位数

            i += t.length() - Math.min(j, k) - 1;

            j = t.length() - 1;

        }

    }

    if (j == -1) { //匹配成功

        return i + 1;

    } else { //匹配失败

        return -1;

    }

}

private static int getLast(String t, char c) {

    for (int i = t.length() - 1; i >= 0; i--) {

        if (t.charAt(i) == c) {

            return i;

        }

    }

    return -1;

}

总结:

Java提供了多种实现字符串匹配算法的方法,我们可以根据问题的需求和数据的规模选择不同的算法。Brute-Force算法最简单、最直接,但时间复杂度较高;KMP算法通过预处理next数组来避免重复比较,效率较高;而Boyer-Moore算法是一种启发式算法,适用于大规模的文本数据匹配。