Java字符串搜索的算法主要包括以下几种:
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);
}
}
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);
}
}
这些算法各有优缺点,适用于不同的场景。选择合适的算法可以显著提高字符串搜索的效率。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。