牛客华为机试HJ52
作者:互联网
1. 问题描述
2. Solution
java版思路分析,来自LeetCode 72
/*
DP
1. Define the state dp[i][j]
to be the minimum number of operations to convert word1[0...i) to word2[0...j)
2. Initial state
For the base case, that is, to convert a string to an empty string, the minimum number of operations(deletions)
is just the length of the string. So we have dp[i][0] = i and dp[0][j] = j.
3. State transition equation
For the general case to convert word1[0...i) to word2[0...j), we break this problem down into sub-problems.
Suppose we have already known how to convert word1[0...i-1) to word2[0...j-1) i.e. dp[i-1][j-1],
if word1[i-1] == word2[j-1], then no more operation is needed and dp[i][j] = dp[i-1][j-1]
if word1[i-1] != word2[j-1], we need to consider three cases.
a) Replace word1[i-1] by word2[j-1] i.e. dp[i][j] = dp[i-1][j-1] + 1
b) if word1[0...i-1) = word2[0...j) then delete word1[i-1] i.e. dp[i][j] = dp[i-1][j] + 1
c) if word1[0...i) + word2[j-1) = word2[0...j) then insert word2[j-1] to word1[0...i)
i.e. dp[i][j] = dp[i][j-1] + 1
So when word1[i-1] != word2[j-1], dp[i][j] will just be the minimum of the above three case
*/
public class Solution {
public int minDistance(String word1, String word2) {
int m = word1.length(), n = word2.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) dp[i][0] = i;
for (int j = 1; j <= n; j++) dp[0][j] = j;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (word1.charAt(i - 1) == word2.charAt(j - 1))
dp[i][j] = dp[i - 1][j - 1];
else
dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])) + 1;
}
}
return dp[m][n];
}
}
本题题解
import sys
if sys.platform != "linux":
file_in = open("input/HJ52.txt")
sys.stdin = file_in
"""
DP
定义: dp[i][j] = s1[i] 与 s2[j] 之间的距离
初始化:
对于边界,是转换一个string到空string,使用删除,所以dp值为原始string的长度
dp[i][0] = i, dp[0][j] = j
状态转移方程:
if s1[i] == s2[j]
dp[i][j] = dp[i-1][j-1]
if s1[i] != s2[j]
a) 替换s2[j] -> s1[i]: dp[i][j] = dp[i - 1][j-1] + 1
b) 删除s1[i]: dp[i][j] = dp[i-1][j] + 1
c) 插入 s1[0...i] + s2[j-1] = s2[0...j]: dp[i][j] = dp[i][j-1] + 1
综上,dp[i][j] = min{dp[i-1][j-1], dp[i-1][j], dp[i][j-1]} + 1
"""
def solve(s1, s2):
m = len(s1)
n = len(s2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
if s1[i - 1] == s2[j - 1]:
dp[i][j] = dp[i - 1][j - 1]
else:
dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1
print(dp[m][n])
while True:
try:
s1 = input().strip()
s2 = input().strip()
solve(s1, s2)
except:
break
标签:...,s2,s1,牛客,word1,word2,机试,dp,HJ52 来源: https://www.cnblogs.com/junstat/p/16172574.html