溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

JAVA中怎么獲取兩個字符串的相似度

發(fā)布時間:2021-06-21 17:43:04 來源:億速云 閱讀:637 作者:Leah 欄目:大數(shù)據(jù)

本篇文章為大家展示了JAVA中怎么獲取兩個字符串的相似度,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。

代碼如下:

public static float getSimilarityRatio(String str, String target) {

	int d[][]; // 矩陣
	int n = str.length();
	int m = target.length();
	int i; // 遍歷str的
	int j; // 遍歷target的
	char ch2; // str的
	char ch3; // target的
	int temp; // 記錄相同字符,在某個矩陣位置值的增量,不是0就是1
	if (n == 0 || m == 0) {
		return 0;
	}
	d = new int[n + 1][m + 1];
	for (i = 0; i <= n; i++) { // 初始化第一列
		d[i][0] = i;
	}

	for (j = 0; j <= m; j++) { // 初始化第一行
		d[0][j] = j;
	}

	for (i = 1; i <= n; i++) { // 遍歷str
		ch2 = str.charAt(i - 1);
		// 去匹配target
		for (j = 1; j <= m; j++) {
			ch3 = target.charAt(j - 1);
			if (ch2 == ch3 || ch2 == ch3 + 32 || ch2 + 32 == ch3) {
				temp = 0;
			} else {
				temp = 1;
			}
			// 左邊+1,上邊+1, 左上角+temp取最小
			d[i][j] = Math.min(Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1), d[i - 1][j - 1] + temp);
		}
	}

	return (1 - (float) d[n][m] / Math.max(str.length(), target.length())) * 100F;
}~~~~

上述內(nèi)容就是JAVA中怎么獲取兩個字符串的相似度,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI