編輯距離
題解
對於兩個字符串,要是將一個字符串轉換爲另一個字符串,可以對一個字符串進行如下的操作。
- 插入一個字符
- 刪除一個字符
- 替換一個字符
那麼對於字符串A
和B
假設A=“examp”, B=“exam”
對於B
在尾部插入一個p
,那麼就相當於在B中不插入p
,將A
中的p
這個字符刪除,同理,在A中插入一個字符,也等同於在B中刪除一個字符。
對於替換的操作,無論是對A字符還是B字符操作都是一樣的。那麼操作可以變成。
- A中插入一個字符
- B中插入一個字符
- 替換一個字符。
定義表示A中字符串前個字符與B中字符串前個字符的編輯距離,那麼個字符與個字符的編輯距離最小爲
同理爲編輯距離,那麼個字符與個字符的編輯距離最小爲
表示A中前個字符與B中前個字符的編輯距離,那麼如果,那麼編輯距離最小爲,如果,那麼編輯距離最小爲。
因此轉移方程爲
對於動態規劃的初始化
那麼和都表示從空字符串轉換到對應的字符串,
代碼
func min(a, b int ) int {
if a< b{
return a
}
return b
}
func minDistance(word1 string, word2 string) int {
len1 := len(word1)
len2 := len(word2)
dp := make([][]int, 0)
for i:=0;i<=len1;i++ {
temp := make([]int, len2+1)
dp = append(dp,temp)
}
for i:=1;i<=len1;i++{
dp[i][0] = i
}
for i:=1;i<=len2;i++{
dp[0][i] = i
}
for i:=1;i<=len1;i++ {
for j:=1;j<=len2;j++ {
if word1[i-1] == word2[j-1] {
dp[i][j] = min(min(dp[i][j-1]+1,dp[i-1][j]+1),dp[i-1][j-1])
} else {
dp[i][j] = min(min(dp[i][j-1]+1,dp[i-1][j]+1),dp[i-1][j-1] + 1)
}
}
}
return dp[len1][len2]
}