Leetcode first click _ Edit Distance

Source: Internet
Author: User

The minimal editing distance is a classic problem. This year, Microsoft intern's written examination has an extended version that involves templates and so on. At that time, a line of code was not written ..

Dp can solve this problem elegantly, and the state transition equation is also very clear. Pos [I] [j] indicates the editing distance between the first I characters of word1 and the first j characters of word2. If the word [I-1] is equal to the word [J-1], the pos [I] [j] is equal to the pos [I-1] [J-1]; otherwise, depending on the several actions edited, you can select one of the three cases with the lowest cost, and delete one character from word1? Delete a character from word2? Modify one of them? The boundary is also very simple. When the length of a string is 0, the editing distance must be based on the length of another string.

Code writing:

class Solution {public:    int minDistance(string word1, string word2) {        int len1 = word1.length(), len2 = word2.length();        int pos[len1+1][len2+1];        for(int i=0;i<=len1;i++)            pos[i][0] = i;        for(int i=0;i<=len2;i++)            pos[0][i] = i;        for(int i=1;i<=len1;i++){            for(int j=1;j<=len2;j++){                if(word1[i-1] == word2[j-1])                    pos[i][j] = pos[i-1][j-1];                else{                    pos[i][j] = min(pos[i-1][j], min(pos[i-1][j-1], pos[i][j-1]))+1;                }            }        }        return pos[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.