leetcode-72-编辑距离
生活随笔
收集整理的這篇文章主要介紹了
leetcode-72-编辑距离
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
問題:
題解:為應用動態規劃,我們定義 dp[i][j] 為從 word1[0..i) 到word2[0..j)轉換的的最小次數。對于基本的情況,將一個字符串轉換為一個空的字符串,所需操作的最小值就是字符串長度本身,因此很明顯: dp[i][0]=i,dp[0][j]=j
對于一般情況,從 word1[0..i) 到 word2[0..j) ,假設我們已知了從 word1[0..i-1) 到 word2[0..j-1) 轉換的次數,可以分兩種情況討論。 if word1[i] == word2[j]
此時的的情況就不用多講,直接dp[i][j]=dp[i-1][j-1]就可以了。
if word1[i] != word2[j]
此時的情況比較復雜,有以下三種可能性。 下邊含義理解為前邊字符串轉為后邊字符串
(1) 替換。如ror和ros,此時進行替換操作,r->s,此時dp[i][j]=dp[i-1][j-1] + 1;
(2) 刪除。如roee和ros,此時進行刪除操作,delete s,此時dp[i][j]=dp[i-1][j] + 1
(3) 插入。如roe和ross,此時進行插入操作,insert s,此時dp[i][j]=dp[i][j-1] + 1 此時可以看出當word1[i] != word2[j] ,dp[i][j] = min(dp[i][j]=dp[i-1][j-1] , dp[i][j]=dp[i][j-1] , dp[i][j]=dp[i-1][j]) + 1 package com.example.demo;public class Test72 {/*** 兩個字符串的編輯距離* e 5 4 4 3* s 4 3 3 2* r 3 2 2 2* o 2 2 1 2* h 1 1 2 3* '' 0 1 2 3* i/j '' r o s* 狀態轉移方程:* 當word1的第i個字符等于,word2的第j個字符,則* dp[i][j] = dp[i-1][j-1]* 當不等于時* dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1*/public int minDistance(String word1, String word2) {if (word1 == null || word2 == null) {return 0;}int len1 = word1.length();int len2 = word2.length();if (len1 == 0 || len2 == 0) {return len1 + len2;}int[][] dp = new int[len1 + 1][len2 + 1];// 初始化 當空串word1,轉換為串word2需要的步數 ,即dp[0][j]// 初試話 當串word1,轉換為空串word2需要的部署,即dp[i][0]for (int i = 0; i < len1 + 1; i++) {dp[i][0] = i;}for (int i = 0; i < len2 + 1; i++) {dp[0][i] = i;}// 動態規劃狀態轉移方程for (int i = 1; i < len1 + 1; i++) {for (int j = 1; j < len2 + 1; 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], Math.min(dp[i][j - 1], dp[i - 1][j - 1])) + 1;}}}return dp[len1][len2];}public static void main(String[] args) {Test72 t = new Test72();int i = t.minDistance("horse", "ros");System.out.println(i);} }
?
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的leetcode-72-编辑距离的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode-67-二进制求和
- 下一篇: leetcode-71-简化路径