[搜索]字符串的相似度问题-从编程之美说起

来源:互联网 发布:java split 效率 编辑:程序博客网 时间:2024/06/05 04:52

在《编程之美》之3.3讲到了计算字符串的相似度,请看下图

原文作者做了很详细的解释,有兴趣的朋友可以参考原文。

其实,总结为一点,是求两个字符的编辑距离,关于编辑距离,可以参考这儿

http://zh.wikipedia.org/wiki/%E7%B7%A8%E8%BC%AF%E8%B7%9D%E9%9B%A2

求两个字符串的编辑距离是有公式的,公式如下:

\qquad\operatorname{lev}_{a,b}(i,j) = \begin{cases}  \max(i,j) & \text{ if} \min(i,j)=0, \\  \min \begin{cases}          \operatorname{lev}_{a,b}(i-1,j) + 1 \\          \operatorname{lev}_{a,b}(i,j-1) + 1 \\          \operatorname{lev}_{a,b}(i-1,j-1) + 1_{(a_i \neq b_j)}       \end{cases} & \text{ otherwise.}\end{cases}


所以,根据这个公式,我们实现代码为:(C++)

int minimum(int a,int b,int c){return min(a,min(b,c));}int LevenshteinDistance(const char* s, int len_s, const char* t, int len_t){/* base case: empty strings */if (len_s == 0) return len_t;if (len_t == 0) return len_s;int cost = 0;/* test if last characters of the strings match */if (s[len_s-1] == t[len_t-1])cost = 0;elsecost = 1;/* return minimum of delete char from s, delete char from t, and delete char from both */return minimum(LevenshteinDistance(s, len_s - 1, t, len_t    ) + 1,LevenshteinDistance(s, len_s    , t, len_t - 1) + 1,LevenshteinDistance(s, len_s - 1, t, len_t - 1) + cost);}

求出来编辑距离,取倒数就是上面提到的相似度。



0 0
原创粉丝点击