Leetcode Edit Distance

Source: Internet
Author: User

Leetcode Edit Distance
Two strings to determine the editing distance between them. You can delete, add, and replace them in three operations. For each operation, the distance is incremented by one. For example, the distance between "AB" and "abc" is 1. Dynamic Planning: use dis [I] [j] to record the distance between the first I of string1 and the first j of string2. So we can know: 1. if the I of str1, that is, str1 [I-1] is equal to the j of str2, that is, str2 [J-1, so dis [I] [j] = dis [I-1] [J-1] 2. if str [I-1]! = Str2 [J-1] 2.1 replace str [I-1] With str2 [J-1] By replacement, then dis [I] [j] = dis [I-1] [J-1] + 1; 2.2 inserting str2 [J-1] After str1 through the insert operation is equivalent to calculating dis [I] [j] = dis [I] [J-1] + 1; 2.3 Insert str1 [I-1] After str2 through the insert operation, that is, dis [I] [j] = dis [I-1] [j] + 1; select the smallest of the three. Iterative update. The Code is as follows: copy the code class Solution {public: int minDistance (string word1, string word2) {int len1 = word1.size (), len2 = word2.size (); if (len1 = 0) return len2; if (len2 = 0) return len1; vector <int> dis (len1 + 1, vector <int> (len2 + 1 )); for (int I = 0; I <= len1; ++ I) {dis [I] [0] = I;} for (int j = 1; j <= len2; ++ j) {dis [0] [j] = j ;}for (int I = 1; I <= len1; ++ I) for (int j = 1; j <= len2; ++ j) {If (word1 [I-1]! = Word2 [j-1]) {dis [I] [j] = min (dis [I-1] [J-1] + 1, dis [I-1] [j] + 1 ); dis [I] [j] = min (dis [I] [J-1] + 1, dis [I] [j]);} else dis [I] [j] = dis [I-1] [J-1];} return dis [len1] [len2];};

Contact Us

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.