zoukankan      html  css  js  c++  java
  • LeetCode(72) Edit Distance

    题目

    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

    分析

    编辑距离问题:
    编辑距离(Edit Distance),又称Levenshtein距离,是指两个字串之间,由一个转成另一个所需的最少编辑操作次数。许可的编辑操作包括将一个字符替换成另一个字符,插入一个字符,删除一个字符。

    一般来说,编辑距离越小,两个串的相似度越大。

    例如将kitten一字转成sitting:

    sitten (k→s)

    sittin (e→i)

    sitting (→g)

    俄罗斯科学家Vladimir Levenshtein在1965年提出这个概念。

    首先定义这样一个函数——edit(i, j),它表示第一个字符串的长度为i的子串到第二个字符串的长度为j的子串的编辑距离。

    显然可以有如下动态规划公式:

    if i == 0j == 0,edit(i, j) = 0
    
    if i == 0j > 0,edit(i, j) = j
    
    if i > 0j == 0,edit(i, j) = i
    
    if i1j1 ,
    
        edit(i, j) == min{ edit(i-1, j) + 1, edit(i, j-1) + 1, edit(i-1, j-1) + f(i, j) }
    
        当第一个字符串的第i个字符不等于第二个字符串的第j个字符时,f(i, j) = 1;否则,f(i, j) = 0

    AC代码

    //编辑距离问题属于动态规划
    class Solution {
    public:
        int minDistance(string word1, string word2) {
            //若其中一个字符串为空,则最短编辑距离为另一字符串的长度
            if (word1.empty())
                return word2.size();
            else if (word2.empty())
                return word1.size();
    
            //注意下标处理
            int m = word1.size() + 1, n = word2.size() + 1;
    
            //记录编辑距离的二维数组
            vector<vector<int> > distance(m, vector<int>(n, 0));
            for (int i = 0; i < m; i++)
                distance[i][0] = i;
            for (int j = 0; j < n; j++)
                distance[0][j] = j;
    
            for (int i = 1; i < m; i++)
            {
                for (int j = 1; j < n; j++)
                {
                    if (word1[i-1] == word2[j-1])
                        distance[i][j] = distance[i - 1][j - 1];
                    else
                        distance[i][j] = distance[i - 1][j - 1] + 1;
    
                    distance[i][j] = min(distance[i][j], min(distance[i - 1][j] + 1, distance[i][j - 1] + 1));
                }//for
            }//for
            return distance[m - 1][n - 1];
        }
    };

    GitHub测试程序源码

  • 相关阅读:
    c3p0连接池c3p0-config.xml配置文件各属性的意义
    MVC案例-架构分析
    jsp中文乱码
    JSP标签
    JSP_include指令
    JavaWeb_请求转发
    JavaWeb_域对象的属性操作
    JavaWeb_JSP语法
    345. Reverse Vowels of a String
    541. Reverse String II
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214822.html
Copyright © 2011-2022 走看看