要求:计算从txt中读取的两个单词的编辑距离
实现的代码如下:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
public class Edit {
public static String S1=""; //存放从txt中读取的第一个单词
public static String S2=""; //存放从txt中读取的第二个单词
public static String zifu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
public static void editmade(String fileName){
File file = new File(fileName);
int ts=0,cs=0;
Reader reader = null;
try {
reader = new InputStreamReader(new FileInputStream(file));
int tempchar;
tempchar = reader.read();
while(tempchar!=-1){
if(tempchar>=65 && tempchar<=90){ //读取字符为大写字符时
S2=S2+zifu.charAt(tempchar-65); //将与读取字符相同的字符中的字符添加到S2中
ts=1;
}
if(tempchar>=97 && tempchar<=122){ //读取字符为小写字符时
S2=S2+zifu.charAt(26+tempchar-97);
ts=1;
}
if(tempchar<65 && S2.length()!=0 && ts==1 && cs==0){ //已读取完一个单词
S1=S2;
S2="";
ts=0;
cs=1;
}
if(tempchar<65 && S2.length()!=0 && cs==1){ //已读取完两个单词
System.out.println("S1="+S1);
System.out.println("S2="+S2);
System.out.println("最终的编辑距离为:"+editdag(S1,S2));
System.out.println();
S1=""; S2=""; //将S1,S2清空,进行下一轮的读取
ts=0; cs=0;
}
tempchar = reader.read();
}
}catch (Exception e) {
e.printStackTrace();
}
}
public static int editdag(String s1,String s2){ //计算最终编辑距离
int ed[][]=new int[s1.length()+1][s2.length()+1];
for(int i=0;i<=s1.length();i++)
ed[i][0]=i;
for(int j=0;j<=s2.length();j++)
ed[0][j]=j;
for(int i=1;i<=s1.length();i++)
for(int j=1;j<=s2.length();j++){
ed[i][j]=min(ed[i-1][j]+1,ed[i][j-1]+1,ed[i-1][j-1]+diff(i,j));
}
for(int i=0;i<=s1.length();i++){
for(int j=0;j<=s2.length();j++){
System.out.print(ed[i][j]+" | ");
}
System.out.println();
}
return ed[s1.length()][s2.length()];
}
public static int min(int a,int b,int c){ //取三个数中的最小值
if(a<b){
if(a<c)
return a;
else
return c;
}
else{
if(b<c)
return b;
else
return c;
}
}
public static int diff(int i,int j){ //比较两个字符,相同返回0,不同返回1
if(S1.charAt(i-1)==S2.charAt(j-1))
return 0;
else
return 1;
}
public static void main(String args[]){
String s="G:\\edit.txt";
editmade(s);
}
}
实现的结果: