Java實(shí)現(xiàn)字符串匹配的示例代碼
java實(shí)現(xiàn)字符串匹配
暴力匹配
/**
* 暴力匹配
*
* @param str1 需要找的總字符串
* @param str2 需要找到的字符串
* @return 找到的字符串的下標(biāo)
*/
private static int violence(String str1, String str2) {
char[] s1 = str1.toCharArray();
char[] s2 = str2.toCharArray();
int s1Len = s1.length;
int s2Len = s2.length;
// 指針,分別指向兩個(gè)字符串
int i = 0;
int j = 0;
// 保證匹配時(shí)不越界
while (i < s1Len && j < s2Len) {
// 第一個(gè)字符匹配上了
if (s1[i] == s2[j]) {
++i;
++j;
} else {
i -= (j - 1);
j = 0;
}
}
// 判斷是否成功
if (j == s2Len) {
return i - j;
} else {
return -1;
}KMP算法
/**
* KMP算法
*
* @param str1 源字符串
* @param str2 子串
* @param next 匹配值表
* @return 對(duì)應(yīng)下標(biāo),沒(méi)有為-1
*/
private static int kmp(String str1, String str2, int[] next) {
for (int i = 0, j = 0; i < str1.length(); ++i) {
while (j > 0 && str1.charAt(i) != str2.charAt(j)) {
j = next[j - 1];
}
if (str1.charAt(i) == str2.charAt(j)) {
j++;
if (j == str2.length()) {
return i - j + 1;
}
return -1;
}
* @return dest的部分匹配表
private static int[] getkmpNext(String dest) {
int length = dest.length();
int[] next = new int[length];
next[0] = 0;
for (int i = 1, j = 0; i < length; i++) {
while (j > 0 && dest.charAt(i) != dest.charAt(j)) {
if (dest.charAt(i) == dest.charAt(j)) {
next[i] = j;
return next;到此這篇關(guān)于Java實(shí)現(xiàn)字符串匹配的文章就介紹到這了,更多相關(guān)java字符串匹配內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot項(xiàng)目中通過(guò)@Value給參數(shù)賦值失敗的解決方案
十分簡(jiǎn)單易懂的Java應(yīng)用程序性能調(diào)優(yōu)技巧分享
String類(lèi)型轉(zhuǎn)localDate,date轉(zhuǎn)localDate的實(shí)現(xiàn)代碼
spring boot 使用Aop通知打印控制器請(qǐng)求報(bào)文和返回報(bào)文問(wèn)題

