update string match

master
ehlxr 2022-06-19 12:55:01 +08:00
parent c1da2bd955
commit c665ca3b1f
2 changed files with 41 additions and 18 deletions

View File

@ -39,20 +39,25 @@ public class BruteForce {
}
public static int bf(String s, String p) {
int sl = s.length();
int pl = p.length();
int m = s.length();
int n = p.length();
for (int i = 0; i <= sl - pl; i++) {
for (int i = 0; i <= m - n; i++) {
int j = 0;
for (; j < pl; j++) {
if (s.charAt(i) == p.charAt(j)) {
i++;
} else {
for (; j < n; j++) {
// if (s.charAt(i) == p.charAt(j)) {
// i++;
// } else {
// break;
// }
// 如果主串与模式串不匹配,则主串向右移动一个字符,模式串从头开始匹配
if (s.charAt(i + j) != p.charAt(j)) {
break;
}
}
if (j == pl) {
return i - pl;
if (j == n) {
// return i - n;
return i;
}
}

View File

@ -52,15 +52,33 @@ public class Kmp {
for (int i = 0; i <= m - n; i++) {
int j = 0;
while (j < n) {
if (scs[i] == pcs[j]) {
i++;
j++;
} else {
// 当模式串与主串不匹配时,如果**不匹配字符**对应模式串下标大于 j > 0 (非首个模式串字符)
// 并且此字符前一个字符对应字符串部分匹配表中的值 next[j - 1] 也大于 0
// j - next[j - 1] 即模式串为后移的位数,等价于 j 置为 next[j - 1]
// while (j < n) {
// if (scs[i] == pcs[j]) {
// i++;
// j++;
// } else {
// // 当模式串与主串不匹配时,如果**不匹配字符**对应模式串下标大于 j > 0 (非首个模式串字符)
// // 并且此字符前一个字符对应字符串部分匹配表中的值 next[j - 1] 也大于 0
// // j - next[j - 1] 即模式串为后移的位数,等价于 j 置为 next[j - 1]
// if (j > 0 && next[j - 1] > 0) {
// j = next[j - 1];
// } else {
// break;
// }
// }
// }
// if (j == n) {
// return i - n;
// }
for (; j < n; j++) {
if (scs[i + j] != pcs[j]) {
// 暴力匹配算法当模式串和主串不匹配时,主串匹配下标 +1模式串匹配下标置为 0
// KMP 算法优化点在于将模式串下标置为不匹配字符前一个字符对应 next 数组的值
if (j > 0 && next[j - 1] > 0) {
// 当模式串与主串不匹配时,如果**不匹配字符**对应模式串下标大于 j > 0 (非首个模式串字符)
// 并且此字符前一个字符对应字符串部分匹配表中的值 next[j - 1] 也大于 0
// j - next[j - 1] 即模式串为后移的位数,等价于 j 置为 next[j - 1]
j = next[j - 1];
} else {
break;
@ -68,7 +86,7 @@ public class Kmp {
}
}
if (j == n) {
return i - n;
return i;
}
}