1. 程式人生 > >LeetCode打卡之 Edit Distance

LeetCode打卡之 Edit Distance

題目

Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.

You have the following 3 operations permitted on a word:

  • Insert a character
  • Delete a character
  • Replace a character

題目大意就是給出兩個字串,需要經過多少步才能從word1變成word2,可以用的操作為插入,刪除,新增

分析

題目的本質就是讓你求個兩個字串之間的編輯距離,和《演算法概論》(中文版)第177頁中的編輯距離一樣
在這裡我按照我的想法大致解釋一下
假設arr[i][j]

是從從word1[0,i)word2[0,j)的距離,有以下三種情況

  • word1[0,i)word1[0, i-1)插入一個字元word2[j-1]得到
  • word2[0,j)word2[0,j-1)插入一個字元word1[i-1]得到
  • word1[0,i)word1[0,i-1)插入一個word1[i-1]得到,word2[0,j)word2[0,j-1)新增word2[j-1]得到
    以上三種情況對應的距離為
  • arr[i][j] = arr[i-1][j]+1
  • arr[i]]j] = arr[i][j-1] + 1
  • arr[i][j] = arr[i-1][j-1] + (word[i-1]==word[j-1] ? 0 : 1)

程式碼

class Solution {
public:
    int minDistance(string word1, string word2) {
        int m = word1.size();
        int n = word2.size();
        int arr[m+1][n+1];
        for (int i = 0; i <= m; ++i) {
            arr[i][0] = i;
        }
        for (int j = 0; j <= n; ++j){
            arr[
0][j] = j; } for (int i = 1; i <= m; ++i) { for (int j = 1; j <= n; ++j) { int min = arr[i-1][j] + 1; if(min > arr[i][j-1] + 1){ min = arr[i][j-1] + 1; } int diff = word1[i-1] == word2[j-1] ? 0 : 1; if(min > arr[i-1][j-1] + diff){ min = arr[i-1][j-1] +diff; } arr[i][j] = min; } } return arr[m][n]; } };