当前位置:Gxlcms > PHP教程 > 比较两个字符串的相似度

比较两个字符串的相似度

时间:2021-07-01 10:21:17 帮助过:19人阅读

比较两个字符串的相似度

  1. public class Levenshtein {
  2. private int compare(String str, String target) {
  3. int d[][]; // 矩阵
  4. int n = str.length();
  5. int m = target.length();
  6. int i; // 遍历str的
  7. int j; // 遍历target的
  8. char ch1; // str的
  9. char ch2; // target的
  10. int temp; // 记录相同字符,在某个矩阵位置值的增量,不是0就是1
  11. if (n == 0) {
  12. return m;
  13. }
  14. if (m == 0) {
  15. return n;
  16. }
  17. d = new int[n + 1][m + 1];
  18. for (i = 0; i <= n; i++) { // 初始化第一列
  19. d[i][0] = i;
  20. }
  21. for (j = 0; j <= m; j++) { // 初始化第一行
  22. d[0][j] = j;
  23. }
  24. for (i = 1; i <= n; i++) { // 遍历str
  25. ch1 = str.charAt(i - 1);
  26. // 去匹配target
  27. for (j = 1; j <= m; j++) {
  28. ch2 = target.charAt(j - 1);
  29. if (ch1 == ch2) {
  30. temp = 0;
  31. } else {
  32. temp = 1;
  33. }
  34. // 左边+1,上边+1, 左上角+temp取最小
  35. d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + temp);
  36. }
  37. }
  38. return d[n][m];
  39. }
  40. private int min(int one, int two, int three) {
  41. return (one = one < two ? one : two) < three ? one : three;
  42. }
  43. /**
  44. * 获取两字符串的相似度
  45. *
  46. * @param str
  47. * @param target
  48. * @return
  49. */
  50. public float getSimilarityRatio(String str, String target) {
  51. return 1 - (float)compare(str, target)/Math.max(str.length(), target.length());
  52. }
  53. public static void main(String[] args) {
  54. Levenshtein lt = new Levenshtein();
  55. String str = "1#2203NO525FANGXIEROADHUANGPUDISTRICTSHANGHAICHINA";
  56. String target = "1#2203NO525FANGXIEROADSHANGHAICN";
  57. System.out.println("similarityRatio="+ lt.getSimilarityRatio(str, target));
  58. }
  59. }

以上就是比较两个字符串的相似度 的内容,更多相关内容请关注PHP中文网(www.gxlcms.com)!

人气教程排行