温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java字符串搜索有哪些算法

发布时间:2025-10-13 21:12:24 来源:亿速云 阅读:130 作者:小樊 栏目:编程语言

Java字符串搜索的算法主要包括以下几种:

1. 朴素字符串匹配算法(Naive String Matching Algorithm)

  • 原理:从文本串的第一个字符开始,逐个字符地与模式串进行比较。
  • 时间复杂度:最坏情况下为O(n*m),其中n是文本串长度,m是模式串长度。

2. KMP算法(Knuth-Morris-Pratt Algorithm)

  • 原理:通过预处理模式串构建部分匹配表(也称为“前缀函数”),避免在匹配失败时回溯文本串指针。
  • 时间复杂度:O(n+m)。

3. Boyer-Moore算法

  • 原理:从模式串的末尾开始匹配,并利用两个启发式规则(坏字符规则和好后缀规则)来跳过不必要的比较。
  • 时间复杂度:平均情况下为O(n/m),最坏情况下为O(n*m)。

4. Rabin-Karp算法

  • 原理:使用哈希函数计算模式串和文本串子串的哈希值,并通过比较哈希值来快速排除不匹配的情况。
  • 时间复杂度:平均情况下为O(n+m),最坏情况下为O(n*m)。

5. Aho-Corasick算法

  • 原理:适用于多模式匹配问题,构建一个有限状态自动机(Trie树),可以在一次遍历中找到所有模式串的出现位置。
  • 时间复杂度:预处理时间为O(m),匹配时间为O(n)。

6. Sunday算法

  • 原理:从模式串的末尾开始匹配,并利用一个简单的规则来决定下一个比较的位置。
  • 时间复杂度:平均情况下为O(n/m),最坏情况下为O(n*m)。

7. Sunday-McClellan算法

  • 原理:是Sunday算法的改进版,通过更复杂的规则来提高匹配效率。
  • 时间复杂度:平均情况下为O(n/m),最坏情况下为O(n*m)。

Java中的实现示例

KMP算法示例

public class KMPAlgorithm {
    public static int[] computeLPSArray(String pat) {
        int m = pat.length();
        int[] lps = new int[m];
        int len = 0;
        int i = 1;
        
        while (i < m) {
            if (pat.charAt(i) == pat.charAt(len)) {
                len++;
                lps[i] = len;
                i++;
            } else {
                if (len != 0) {
                    len = lps[len - 1];
                } else {
                    lps[i] = 0;
                    i++;
                }
            }
        }
        return lps;
    }

    public static void KMPSearch(String txt, String pat) {
        int n = txt.length();
        int m = pat.length();
        int[] lps = computeLPSArray(pat);
        
        int i = 0;
        int j = 0;
        
        while (i < n) {
            if (pat.charAt(j) == txt.charAt(i)) {
                i++;
                j++;
            }
            
            if (j == m) {
                System.out.println("Found pattern at index " + (i - j));
                j = lps[j - 1];
            } else if (i < n && pat.charAt(j) != txt.charAt(i)) {
                if (j != 0) {
                    j = lps[j - 1];
                } else {
                    i++;
                }
            }
        }
    }

    public static void main(String[] args) {
        String txt = "ABABDABACDABABCABAB";
        String pat = "ABABCABAB";
        KMPSearch(txt, pat);
    }
}

Rabin-Karp算法示例

public class RabinKarpAlgorithm {
    public static int rabinKarpSearch(String txt, String pat) {
        int M = pat.length();
        int N = txt.length();
        int i, j;
        int patHash = 0;
        int txtHash = 0;
        int h = 1;
        int d = 256; // Number of characters in input alphabet
        int q = 101; // A prime number
        
        // The value of h would be "pow(d, M-1)%q"
        for (i = 0; i < M - 1; i++) {
            h = (h * d) % q;
        }
        
        // Calculate the hash value of pattern and first window of text
        for (i = 0; i < M; i++) {
            patHash = (d * patHash + pat.charAt(i)) % q;
            txtHash = (d * txtHash + txt.charAt(i)) % q;
        }
        
        // Slide the pattern over text one by one
        for (i = 0; i <= N - M; i++) {
            // Check the hash values of current window of text and pattern.
            // If the hash values match then only check for characters one by one
            if (patHash == txtHash) {
                // Check for characters one by one
                for (j = 0; j < M; j++) {
                    if (txt.charAt(i + j) != pat.charAt(j)) {
                        break;
                    }
                }
                
                // if pat[0...M-1] = txt[i, i+1, ...i+M-1]
                if (j == M) {
                    System.out.println("Pattern found at index " + i);
                }
            }
            
            // Calculate hash value for next window of text: Remove leading digit, add trailing digit
            if (i < N - M) {
                txtHash = (d * (txtHash - txt.charAt(i) * h) + txt.charAt(i + M)) % q;
                
                // We might get negative value of txtHash, converting it to positive
                if (txtHash < 0) {
                    txtHash = (txtHash + q);
                }
            }
        }
        
        return -1;
    }

    public static void main(String[] args) {
        String txt = "ABCCDDAEFG";
        String pat = "CDD";
        rabinKarpSearch(txt, pat);
    }
}

这些算法各有优缺点,适用于不同的场景。选择合适的算法可以显著提高字符串搜索的效率。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI