topic
Topic connection: Cattle customer network: minimum number of transitions
Given two strings, three ways are known to transform
- Insert a character
- To delete a character
- Changing a character
Please design an algorithm to find the minimum through several transformation between two strings, a string can be converted into a string 2
Enter a description
Two input string, the string length <= 1000
Output Description
The minimum number of transitions
Sample input
hello
helle
Sample Output
1
AC Code
import java.util.Scanner;
/**
* 典型的动态规划题目
*
* 可以用dp[i][j]来表示str1在i位置之前和str2在j位置之前字符的最小变换次数,
* 那么dp[i][j]的取值与当前位置字符的判断有关。
*
* 递推公式:
*
* str1[i] == str2[j]
* => dp[i][j] = dp[i-1][j-1]
*
* str1[i] != str2[j]
* => dp[i][j] = min(dp[i-1][j-1], dp[i][j-1], dp[i-1][j]) + 1
*
* 为了初始化方便,可以在str1和str2的首部添加一个哨兵字符
* 例如:
*
* # e k k o
* # 0 1 2 3 4
* h 1 2 3 4 3
* e 2 1 2 3 4
* k 3 2 1 2 3
* k 4 3 2 1 2
* o 5 4 3 2 1
*
*/
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str1 = "#" + scanner.next();
String str2 = "#" + scanner.next();
int[][] dp = new int[str1.length()][str2.length()];
// 初始化
for (int i = 1; i < str1.length(); i++)
dp[i][0] = i;
for (int i = 1; i < str2.length(); i++)
dp[0][i] = i;
for (int i = 1; i < str1.length(); i++) {
for (int j = 1; j < str2.length(); j++) {
if (str1.charAt(i) == str2.charAt(j))
dp[i][j] = dp[i - 1][j - 1];
else {
dp[i][j] = Math.min(dp[i - 1][j - 1],
Math.min(dp[i][j - 1], dp[i - 1][j])) + 1;
}
}
}
System.out.println(dp[str1.length() - 1][str2.length() - 1]);
}
}