編輯距離 dp_使用動態編程(DP)編輯距離

編輯距離 dp

Problem: You are given two strings s1 and s2 of length M and N respectively. You can perform following operations on the string.

問題:給您兩個長度分別為MN的字符串s1s2 。 您可以對字符串執行以下操作。

  1. Insert a character at any position

    在任意位置插入字符

  2. Delete a character at any position

    刪除任意位置的字符

  3. Replace a character with any character at any position

    用任意位置的任何字符替換字符

Find minimum number of ways to convert s1 into s2 using above operation only.

僅使用上述操作找出將s1轉換為s2的最小方法。

Constraints:

限制條件:

1 <= N <= 2000
1 <= M <= 2000

Example:

例:

    Sample Input 1:
abcde
bcdae
Sample Output 1:
2
Sample Input 2:
dacef
cdafe
Sample Output 2:
3

Explanation of the problem:

問題說明:

In the first sample provided above, we can delete a from s1 and insert it before e in s1. So, there are two steps.

在上面提供的第一個示例中,我們可以從s1中刪除a并將其插入s1中的 e之前。 因此,有兩個步驟。

Solution:

解:

Before proceeding to the solution we can see that the recursive solution will be hard to implement so we will proceed to the dynamic programming approach. In this approach, the jth cell of ith row represents the minimum number of changes needed to change s1(ith index to end) and s2(jth index to end). Now if an ith character of s1 is equal to a jth character of s2 then we don’t have to take care of that character as it is already same so pick up the right-bottom diagonal value. If characters are not equal then we can delete the ith character of the s1 or jth character of s2, replace the ith character of s1 with the jth character of s2 or vice versa and move on to the right bottom corner. In this case, we also have to add 1 as deletion, replacement is considered as a step.

在繼續解決方案之前,我們可以看到遞歸解決方案將很難實現,因此我們將繼續使用動態編程方法。 在這種方法中, i行的 j 單元表示更改s1( i 索引到結束)和s2( j 索引到結束)所需的最小更改次數。 現在,如果s1的 i 字符等于s2的 j 字符,那么我們就不必照顧這個字符了,因為它已經是相同的了,所以選擇右下角的對角線值。 如果字符不相等,那么我們可以刪除s1的 i 字符或s2的 j 字符,將s1的 i 字符替換為s2的 j 字符,反之亦然,然后移至右下角。 在這種情況下,我們還必須添加1作為刪除,替換被視為一個步驟。

Algorithm:

算法:

  1. Create dp matrix in which jth cell of ith row represents the minimum number of ways to change the string s1 (from ith index to last) and string s2 (jth index to last).

    創建dp矩陣,其中 i行的 j 單元格表示更改字符串s1 (從 i 索引到最后一個)和字符串s2 ( j 索引到最后一個)的最小方式。

  2. One extra row and col are taken to build to include blank string also.

    還需要多一行和col來構建以包括空白字符串。

  3. If s1 is blank and s2 is full we have to initialize this condition so initializing this condition doing the same thing for vice versa case.

    如果s1為空白,而s2為滿,則必須初始化此條件,因此對這種情況進行初始化的情況與之相反。

  4. Start filling dp matrix from the Nth row and Mth column (right to left and down to up).

    開始從 N行和M填充DP矩陣 (從右到左,下到上)。

  5. Find the answer of each row by using dp relations.

    通過使用dp關系找到每一行的答案。

  6. If ith character of s1 is same as a jth character of s2 then store the right-bottom value.

    如果I S1字符是相同的 j S2的字符然后存儲右下角值。

  7. Otherwise, take the minimum of downward adjacent, rightward adjacent, bottom-right adjacent value and add 1 to it and store the answer.

    否則,取下相鄰,右相鄰,右下相鄰值中的最小值,并將其加1并存儲答案。

  8. Store the answer in a jth cell of an ith row.

    將答案存儲在 i行的 j 單元格中。

The time complexity of the above code is O (N * M).

上面代碼的時間復雜度是O(N * M)。

使用動態編程(DP)編輯距離的C ++代碼 (C++ Code for Edit Distance using Dynamic Programming (DP))

#include <iostream>
#include <math.h>
using namespace std;
// function for finding edit distance
int editDistance(string s1, string s2){
// dp matrix for storing the values
int dp[s1.length() + 1][s2.length() + 1] = {0};
int counter = 0;
// loops are used to store some values necessary for dp relations as 
// we can initialize all values to 0 in this case
for(int row = s1.length();row>=0;row--){
dp[row][s2.length()] = counter;
counter++;
}
counter = 0;
for(int col = s2.length();col>=0;col--){
dp[s1.length()][col] = counter;
counter++;
}
// filling the dp matrix 
for(int row = s1.length()-1;row>=0;row--){
for(int col = s2.length() - 1;col>=0;col--){
// if rowth character of s1 is same as colth character of s2 
// then store diagonally right-bottom shifted value
if(s1[row] == s2[col]){
dp[row][col] = dp[row+1][col+1];
}
// otherwise, take minimum of adjacent downward, adjacent rightward, 
// diagonally rigth-bottom value and add 1 to it and store that value
else{
dp[row][col] = min(dp[row+1][col], min(dp[row][col+1], dp[row+1][col+1])) + 1;
}
}
}
return dp[0][0];
}
// driver function to test the code
int main() {
string s1,s2;
cin >> s1 >> s2;
cout << s1 << "\n" << s2 << endl;
cout<< editDistance(s1, s2);
return 0;
}

Output

輸出量

abcde
bcdae
abcde
bcdae
2   

翻譯自: https://www.includehelp.com/algorithms/edit-distance-using-dynamic-programming.aspx

編輯距離 dp

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/541915.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/541915.shtml
英文地址,請注明出處:http://en.pswp.cn/news/541915.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

tomcat +apache 配置集群

2019獨角獸企業重金招聘Python工程師標準>>> APACHE2.2.25TOMCAT6.0.37配置負載均衡 目標: 使用 apache 和 tomcat 配置一個可以應用的 web 網站&#xff0c;要達到以下要求&#xff1a; 1. Apache 做為 HttpServer &#xff0c;后面連接多個 tomcat 應用實例&…

java雙緩存機制_詳解JVM類加載機制及類緩存問題的處理方法

前言大家應該都知道&#xff0c;當一個Java項目啟動的時候&#xff0c;JVM會找到main方法&#xff0c;根據對象之間的調用來對class文件和所引用的jar包中的class文件進行加載(其步驟分為加載、驗證、準備、解析、初始化、使用和卸載)&#xff0c;方法區中開辟內存來存儲類的運…

oracle中dbms_并發和由于DBMS中的并發導致的問題

oracle中dbms并發 (Concurrency) The ability of a database system which handles simultaneously or a number of transactions by interleaving parts of the actions or the overlapping this is called concurrency of the system. 數據庫系統通過交織部分操作或重疊操作來…

什么是mvc?

什么是MVCMVC 是一種設計模式&#xff0c;它將應用劃分為3 個部分&#xff1a;數據&#xff08;模型&#xff09;、展現層&#xff08;視圖&#xff09;和用戶交互層&#xff08;控制器&#xff09;。換句話說&#xff0c;一個事件的發生是這樣的過程&#xff1a;1&#xff0e;…

mysql的安裝和基本命令_MySQL安裝以及簡單命令用法

MYSQL:關系型數據庫存儲引擎:負責將邏輯層的概念轉化為物理層機制&#xff0c;在物理層完成物理機制。支持事務&#xff1a;transaction必須滿足的條件&#xff1a;ACID(一致性,持久性,原子性,隔離性)鎖&#xff1a;并發訪問隨機訪問&#xff1a;數據在磁盤上是隨機存儲的安裝&…

將數組轉換為JavaScript中的對象

Lets say you have the following array, 假設您有以下數組&#xff0c; const nums [1, 2, 3, 4, 5];console.log(nums);Output 輸出量 (5) [1, 2, 3, 4, 5]We know that nums is an array and we can see in the output that we get an array. Lets convert it into an ob…

docker集群運行在calico網絡上

2019獨角獸企業重金招聘Python工程師標準>>> ##網絡及版本信息 docker1 centos7 192.168.75.200 docker2 centos7 192.168.75.201 物理網絡 192.168.75.1/24 Docker version 1.10.3, build 3999ccb-unsupported &#xff0c;安裝過程略 # calicoctl version Version…

python批量雷達圖_python批量制作雷達圖

老板要畫雷達圖&#xff0c;但是數據好多組怎么辦&#xff1f;不能一個一個點excel去畫吧&#xff0c;那么可以利用python進行批量制作&#xff0c;得到樣式如下&#xff1a;首先制作一個演示的excel&#xff0c;評分為excel隨機數生成&#xff1a;1 INT((RAND()4)*10)/10加入標…

JavaScript中帶有示例的Math.log()方法

JavaScript | Math.log()方法 (JavaScript | Math.log() Method) Math.log() is a function in math library of JavaScript that is used to return the value of natural Log i.e. (base e) of the given number. It is also known as ln(x) in mathematical terms. Math.log…

SUI踩坑記錄

SUI踩坑記錄 最近做了個項目選型了SUI和vue做單頁應用。下面記錄一下踩坑經歷SUI 介紹 sui文檔&#xff1a;http://m.sui.taobao.org/SUI Mobile 是一套基于 Framework7 開發的UI庫。它非常輕量、精美&#xff0c;只需要引入我們的CDN文件就可以使用&#xff0c;并且能兼容到 i…

java 寫入xml文件_java讀寫xml文件

要讀的xml文件李華姓名>14年齡>學生>張三姓名>16年齡>學生>學生花名冊>package xml;import java.io.FileOutputStream;import java.io.OutputStreamWriter;import java.io.Writer;import java.util.Iterator;import java.util.Vector;import javax.xml.pa…

JavaScript中帶有示例的Math.max()方法

JavaScript | Math.max()方法 (JavaScript | Math.max() Method) Math.max() is a function in math library of JavaScript that is used to return the greatest value of all the passed values to the method. Math.max()是JavaScript數學庫中的函數&#xff0c;用于將所有…

java 修飾符默認_Java和C#默認訪問修飾符

C#中&#xff1a;針對下面幾種類型內部成員的訪問修飾符&#xff1a;enum的默認訪問修飾符&#xff1a;public。class的默認為private。interface默認為public。struct默認為private。其中&#xff1a;public可以被任意存取&#xff1b;protected只可以被本類和其繼承子類存取&…

JavaScript中帶有示例的Math.abs()方法

JavaScript | Math.abs()方法 (JavaScript | Math.abs() Method) Math operations in JavaScript are handled using functions of math library in JavaScript. In this tutorial on Math.abs() method, we will learn about the abs() method and its working with examples.…

人臉識別python face_recognize_python2.7使用face_recognition做人臉識別

偶然看到一篇文章&#xff0c;說是可以實時人臉識別&#xff0c;很有興趣就自己按照文章開始動手人臉識別&#xff0c;但是實現過程中遇到了幾個問題這里做個總結&#xff0c;希望可以幫助到大家安裝face_recognition這個之前需要先安裝編譯dlib&#xff0c;如果沒有安裝dlib&a…

c# reverse_清單 .Reverse()方法,以C#為例

c# reverseC&#xff03;List <T> .Reverse()方法 (C# List<T>.Reverse() Method) List<T>.Reverse() method is used to reverse the all list elements. List <T> .Reverse()方法用于反轉所有列表元素。 Syntax: 句法&#xff1a; void List<T&…

cpuinfo詳解

cat /proc/cpuinfo processor: 23&#xff1a;超線程技術的虛擬邏輯核第24個 ###一般看最后一個0...23 表示24線程 vendor_id: GenuineIntel&#xff1a;CPU制造商cpu family: 6&#xff1a;CPU產品系列代號model: 44&#xff1a;CPU屬于其系列中的哪一代號model name: Intel…

jvm延遲偏向_用于偏向硬幣翻轉模擬的Python程序

jvm延遲偏向Here, we will be simulating the occurrence coin face i.e. H - HEAD, T - TAIL. Simply we are going to use an inbuilt library called as random to call a random value from given set and thereby we can stimulate the occurrence value by storing the o…

java項目沒有bin_WebAPI項目似乎沒有將轉換后的web.config發布到bin文件夾?

我很擅長.NET配置轉換 . 我現在將它們放在用于數據使用的類庫和WPF應用程序上 .但是&#xff0c;當我嘗試使用ASP.NET WebAPI項目進行設置時&#xff0c;似乎發生了一些奇怪的事情 .配置文件永遠不會顯示在我的bin目錄中&#xff0c;因此web.config始終顯示為預先形成的配置文件…