比較兩個字符串的相似度,核心算法是用一個2維數組記錄每個字符串是否相同,如果相同記為0,不相同記為1,每行,每列的相同個數累加,則數組最后一個數為不相同個數的總數。從而判斷這兩個字符串的相似度,在判斷大小寫時,沒有區分大小寫,即大小寫視為相同的字符。
package com.qinsoft.test; public class Levenshtein { private int compare(String str, String target) { int d[][]; // 矩陣 int n = str.length(); int m = target.length(); int i; // 遍歷str的 int j; // 遍歷target的 char ch1; // str的 char ch2; // target的 int temp; // 記錄相同字符,在某個矩陣位置值的增量,不是0就是1 if (n == 0) { return m; } if (m == 0) { return n; } 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 ch1 = str.charAt(i - 1); // 去匹配target for (j = 1; j <= m; j++) { ch2 = target.charAt(j - 1); if (ch1 == ch2 || ch1 == ch2+32 || ch1+32 == ch2) { temp = 0; } else { temp = 1; } // 左邊+1,上邊+1, 左上角+temp取最小 d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + temp); } } return d[n][m]; } private int min(int one, int two, int three) { return (one = one < two ? one : two) < three ? one : three; } /** * 獲取兩字符串的相似度 */ public float getSimilarityRatio(String str, String target) { return 1 - (float) compare(str, target) / Math.max(str.length(), target.length()); } public static void main(String[] args) { Levenshtein lt = new Levenshtein(); String str = "中國"; String target = "中文"; System.out.println("similarityRatio=" + lt.getSimilarityRatio(str, target)); } }