比较 JavaScript 中的字符串并返回相似度百分比
我们需要编写一个 JavaScript 函数,它可以比较两个字符串并返回它们相似程度的百分比。此百分比将只不过是两个字符串中具有公共字符的度量。
如果它们完全相似,则输出应为 100,如果它们根本不包含公共字符,则输出应为 0。
示例
const calculateSimilarity = (str1 = '', str2 = '') => { let longer = str1; let shorter = str2; if (str1.length < str2.length) { longer = str2; shorter = str1; } let longerLength = longer.length; if (longerLength == 0) { return 1.0; } return +((longerLength - matchDestructively(longer, shorter)) / parseFloat(longerLength) * 100).toFixed(2); }; const matchDestructively = (str1 = '', str2 = '') => { str1 = str1.toLowerCase(); str2 = str2.toLowerCase(); let arr = new Array(); for (let i = 0; i <= str1.length; i++) { let lastValue = i; for (let j = 0; j <= str2.length; j++) { if (i == 0){ arr[j] = j; }else if(j > 0){ let newValue = arr[j - 1]; if(str1.charAt(i - 1) != str2.charAt(j - 1)) newValue = Math.min(Math.min(newValue, lastValue), arr[j]) + 1; arr[j - 1] = lastValue; lastValue = newValue; } } if (i > 0) arr[str2.length] = lastValue; } return arr[str2.length]; }; console.log(calculateSimilarity('Mathematics','Mathamatecs'));
输出
这将产生以下输出 -
[ [ 1, 10, 100 ], [ 1, 10, 200 ], [ 1, 10, 300 ], [ 1, 20, 100 ], [ 1, 20, 200 ], [ 1, 20, 300 ], [ 2, 10, 100 ], [ 2, 10, 200 ], [ 2, 10, 300 ], [ 2, 20, 100 ], [ 2, 20, 200 ], [ 2, 20, 300 ] ]
广告