Minimum distance between strings
DP; Medium;
1. Link
2. 描述
示例1
"aaa","bbb"0牛牛可以将S1中的字符'a'全部替换成字符'b',这样S1就变成了"bbb",那么S1和S2的距离就是0示例2
"aabb","cdef"备注:
3. 思路: 2D-DP
4. Coding
Last updated
DP; Medium;
"aaa","bbb"0牛牛可以将S1中的字符'a'全部替换成字符'b',这样S1就变成了"bbb",那么S1和S2的距离就是0"aabb","cdef"Last updated
3一种可行的方案是将S1中的字符'a'全部替换成字符'c',那么S1变成了"ccbb",和S2的距离是3S1.size() =S2.size()S1.size()=S2.size()1 \leq S1.size() \leq 5 * 10^41≤S1.size()≤5∗104
S1和S2中的字母均为小写字母class Solution:
def GetMinDistance(self , s1 , s2 ):
#
#method1: 2D-DP
# build a table with column and row = dictionary of 26 char
# dp[i][j] = count of the case when s1[i]= i^th char and s2[j] = j^th char
# then
# we iterate every char in row and find the max dp[i][j] on this row
# then we compute the different between max dp[i][j] and dp[i][i]
# to see if we replace the i^th char in s1, the maximum distance we can subtract
# do this over every char and find the char that has maximum different
#
# the final distance = the original distance - max different + abs(len(s1) - len(s2)) the length different
# Time: O(n) + O(26*26) = O(n)
#
dp= [[0]*26 for i in range(26)]
dist = 0
for i in range(len(s1)):
r= ord(s1[i]) - ord('a')
if i < len(s2):
c = ord(s2[i]) -ord('a')
dp[r][c] += 1
if s1[i] != s2[i]:
dist += 1
cnt = -float('inf')
for i in range(26):
max_ocur = 0
cnt_sum = 0
for j in range(26):
max_ocur = max(max_ocur, dp[i][j])
cnt_sum += dp[i][j]
cnt = max(cnt, max_ocur - dp[i][i])
dist = dist - cnt + abs(len(s1) - len(s2))
return dist