Lucene4.3.1字符串距离接口StringDistance实现之LevensteinDistance源码解析

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/asty9000/article/details/81489004

LevensteinDistance是LevenshteinDistance算法的实现,采用三个一维数组代替了一个二维数组,一个数组为上一轮计算的值,一个数组保存本轮计算的值,最后一个数组用于交换两个数组的值。

package org.apache.lucene.search.spell;


public final class LevensteinDistance implements StringDistance {


    public LevensteinDistance () {
    }

    @Override
    public float getDistance (String target, String other) {
      char[] sa;
      int n;
      int p[]; //上一行计算的值
      int d[]; //当前行计算的值
      int _d[]; //用于交换p和d
      
        

        sa = target.toCharArray();
        n = sa.length;
        p = new int[n+1]; 
        d = new int[n+1]; 
      
        final int m = other.length();
        if (n == 0 || m == 0) {
          if (n == m) {
            return 1;
          }
          else {
            return 0;
          }
        } 


        int i; // target的索引
        int j; // other的索引

        char t_j; //other的第j个字符

        int cost; 
		//初始化,将空字符串转换为长度为i的target字符串的操作次数
        for (i = 0; i<=n; i++) {
            p[i] = i;
        }
		
        for (j = 1; j<=m; j++) {
            t_j = other.charAt(j-1);
            //左方的初始值为将长度为j的other字符串转换为空字符串的操作次数
			d[0] = j;
			//计算将长度为i的target字符串转换为长度为j的other字符串的操作次数
            for (i=1; i<=n; i++) {
                cost = sa[i-1]==t_j ? 0 : 1;
				//d[i-1]左方、p[i]上方、p[i-1]左上
                d[i] = Math.min(Math.min(d[i-1]+1, p[i]+1),  p[i-1]+cost);
            }

            //交换p和d,用于下一轮计算
            _d = p;
            p = d;
            d = _d;
        }

		//计算相似度,p中最后一个元素为LevensteinDistance
        return 1.0f - ((float) p[n] / Math.max(other.length(), sa.length));
    }

  @Override
  public int hashCode() {
    return 163 * getClass().hashCode();
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj) return true;
    if (null == obj) return false;
    return (getClass() == obj.getClass());
  }

  @Override
  public String toString() {
    return "levenstein";
  }
}

猜你喜欢

转载自blog.csdn.net/asty9000/article/details/81489004