# Leetcode DP edit distance

Source: Internet
Author: User

Edit distance total accepted: 14997 total submissions: 59129my submissions

Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step .)

You have the following 3 operations permitted on a word:

A) insert a character
B) delete a character
C) replace a character

Question: If you have two words, you can add, delete, or replace one character. How many operations do you need to perform to change the first word to the second one?
Idea: DP
F [I] [J] indicates the minimum editing distance from word1 [1. J] To word2 [1. I ].
If word2 [I] = word1 [J], F [I] [J] = f [I-1] [J-1]
Else f [I] [J] = min {f [I-1] [J-1], F [I] [J-1], f [I-1] [J]} + 1
Complexity: time O (N), Space O (1)

`Int mindistance (string word1, string word2) {If (word1.empty () return word2.size (); If (word2.empty () return word1.size (); vector <vector <int> dp (word1.size () + 1, vector <int> (word2.size () + 1, 0 )); /// initialize for (INT I = 0; I <= word1.size (); ++ I) DP [I] [0] = I; for (Int J = 0; j <= word2.size (); ++ J) DP [0] [J] = J; // Iteration for (INT I = 0; I <word1.size (); ++ I) {for (Int J = 0; j <word2.size (); ++ J) {int II = I + 1, JJ = J + 1; if (word1 [I] = word2 [J]) DP [II] [JJ] = DP [II-1] [JJ-1]; else DP [II] [JJ] = min (DP [II] [JJ-1], DP [II-1] [JJ]), DP [II-1] [JJ-1]) + 1 ;}} return DP [word1.size ()] [word2.size ()];}`

Leetcode DP edit distance

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.