编辑距离(动态规划)


public class 编辑距离 {
	private static char str1[] = "Male".toCharArray();
	private static char str2[] = "Female".toCharArray();
	private static char str3[] = "Male".toCharArray();
	private static char str4[] = "Man".toCharArray();
	private static char str5[] = "Adult".toCharArray();
	private static char str6[] = "Male".toCharArray();
	public static int min(int a, int b) {
		return (a > b ? b : a);
	}

	public static int minval(int a, int b, int c) {
		int zhi = min(a, b);
		int minvalue = min(zhi, c);
		return minvalue;
	}

	void editDistance(char[] str1, char[] str2) {
		int lenthofstr1 = str1.length;
		int lenthofstr2 = str2.length;
		int distance[][] = new int[lenthofstr1 + 1][lenthofstr2 + 1];
		// 变量用来遍历、初始化字符串
		int i, j;

		for (i = 0; i < lenthofstr1 + 1; i++) {
			distance[i][0] = i;
		}
		for (i = 0; i < lenthofstr2 + 1; i++) {
			distance[0][i] = i;
		}
		for (i = 1; i < lenthofstr1 + 1; i++) {
			for (j = 1; j < lenthofstr2 + 1; j++) {
				// 如果对应的字符相等,原问题交给子问题处理,即不用任何操作
				if (str1[i - 1] == str2[j - 1]) {
					distance[i][j] = distance[i - 1][j - 1];
				} else {
					// 否则的话,对左、右、左上角的值进行求最小值
					distance[i][j] = minval(distance[i - 1][j] + 1, distance[i][j - 1] + 1, distance[i - 1][j - 1] + 1);
				}
				System.out.print(distance[i][j] + " ");
			}
			System.out.println();
		}
		System.out.println("最少的操作次数是:" + distance[lenthofstr1][lenthofstr2]);
		System.out.println("d(string1,string2)=" + distance[lenthofstr1][lenthofstr2]);
	}

	public static void main(String[] args) {
		编辑距离 a=new 编辑距离();
		a.editDistance(str1, str2);
		a.editDistance(str3, str4);
		a.editDistance(str5, str6);
	}

}

 

你可能感兴趣的:(编辑距离(动态规划))