zoukankan      html  css  js  c++  java
  • Levenshtein Distance,判断字符串的相似性

            private int LevenshteinDistance(string s1,string s2,int maxValue)
            {
                if (s1 == null|| s1.Length == 0) return maxValue;
                if (s2 == null|| s2.Length == 0) return maxValue;
                if (s1.Trim() == s2.Trim()) return 0;
                // create two work vectors of integer distances
                int[] v0 = new int[s2.Length + 1];
                int[] v1 = new int[s2.Length + 1];
                int[] vtemp;
                // initialize v0 (the previous row of distances)
                // this row is A[0][i]: edit distance for an empty s
                // the distance is just the number of characters to delete from t
                for (int i = 0; i < v0.Length; i++)
                {
                    v0[i] = i;
                }
                for (int i = 0; i < s1.Length; i++)
                {
                    // calculate v1 (current row distances) from the previous row v0
                    // first element of v1 is A[i+1][0]
                    //   edit distance is delete (i+1) chars from s to match empty t
                    v1[0] = i + 1;
                    // use formula to fill in the rest of the row
                    for (int j = 0; j < s2.Length; j++)
                    {
                        int cost = 1;
                        if (s1.Substring(i, 1) == s2.Substring(j, 1))
                        {
                            cost = 0;
                        }
                        v1[j + 1] = Math.Min(
                            v1[j] + 1,              // Cost of insertion
                            Math.Min(
                                v0[j + 1] + 1,  // Cost of remove
                                v0[j] + cost)); // Cost of substitution
                    }
                    // copy v1 (current row) to v0 (previous row) for next iteration
                    //System.arraycopy(v1, 0, v0, 0, v0.length);
                    // Flip references to current and previous row
                    vtemp = v0;
                    v0 = v1;
                    v1 = vtemp;
                }
                return Math.Min(v0[s2.Length],maxValue);
            }
    

      

  • 相关阅读:
    Spring shiro 初次使用小结
    Spring data Redis
    Redis 学习相关的网站
    Spring依赖注入 — util命名空间配置
    添加至数据库的中文显示问号
    freemarker的classic_compatible设置,解决报空错误
    HTTP协议
    Maven添加本地Jar包
    java中的字符串分割函数
    读取文件方法大全
  • 原文地址:https://www.cnblogs.com/panpanwelcome/p/7449813.html
Copyright © 2011-2022 走看看