編輯距離演算法的實現
阿新 • • 發佈:2019-01-26
編輯距離(Edit Distance),又稱Levenshtein距離,是指兩個字串之間,由一個轉成另一個所需的最少編輯操作次數。許可的編輯操作包括將一個字元替換成另一個字元,插入一個字元,刪除一個字元。一般來說,編輯距離越小,兩個串的相似度越大。
例如將kitten一字轉成sitting:
sitten (k→s)
sittin (e→i)
sitting (→g)
比如要計算cafe和coffee的編輯距離。cafe→caffe→coffe→coffee
先建立一個6×8的表(cafe長度為4,coffee長度為6,各加2)
(1):
接著,在如下位置填入數字(表2):
從3,3格開始,開始計算。取以下三個值的最小值:
迴圈操作,推出下表
c | o | f | f | e | e |
c | |||||
a | |||||
f | |||||
e | 表 | 1 |
c | o | f | f | e | e | |
0 | 1 | 2 | 3 | 4 | 5 | 6 |
c | 1 | |||||
a | 2 | |||||
f | 3 | |||||
e | 4 | 表 | 2 |
- 如果最上方的字元等於最左方的字元,則為左上方的數字。否則為左上方的數字+1。(對於3,3來說為0)
- 左方數字+1(對於3,3格來說為2)
- 上方數字+1(對於3,3格來說為2)
c | o | f | f | e | e | |
0 | 1 | 2 | 3 | 4 | 5 | 6 |
c | 1 | 0 |
||||
a | 2 | |||||
f | 3 | |||||
e | 4 | 表 | 3 |
c | o | f | f | e | e | ||
0 | 1 | 2 | 3 | 4 | 5 | 6 | |
c | 1 | 0 | 1 | 2 | 3 | 4 | 5 |
a | 2 | 1 | 1 | 2 | 3 | 4 | 5 |
f | 3 | 2 | 2 | 1 | 2 | 3 | 4 |
e | 4 | 3 | 3 | 2 | 2 | 2 | 3 |
取右下角,得編輯距離為3
程式碼實現如下:
import java.util.Scanner; import java.util.regex.Pattern; public class Test{ public static void main(String[] args) { Scanner input=new Scanner(System.in); String s1=input.nextLine(); String s2=input.nextLine(); compare(s1,s2); input.close(); } public static void compare(String s1,String s2){ int m=s1.length(); int n=s2.length(); int c[][]=new int[m+1][n+1]; for(int i=0;i<m+1;i++){ c[0][i]=i; } for(int j=0;j<n+1;j++){ c[j][0]=j; } for(int i=1;i<m+1;i++){ for(int j=1;j<n+1;j++){ if(s1.charAt(i-1)==s2.charAt(j-1)){ c[i][j]=min(c[i-1][j]+1,c[i][j-1]+1,c[i-1][j-1]); }else{ c[i][j]=min(c[i-1][j]+1,c[i][j-1]+1,c[i-1][j-1]+1); } } } System.out.println("****"); for(int i=0;i<m+1;i++){ for(int j=0;j<n+1;j++){ System.out.print(c[i][j]+" "); } System.out.println(""); } System.out.println("****"); } public static int min(int a,int b,int c){ return a<b?(a<c?a:c):(b>c?c:b); } }