Skip to content

72. Edit Distance

难度Hard

刷题内容

原题连接

  • https://leetcode.com/problems/edit-distance/

内容描述

You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.

Example 1:

Input:
  s = "barfoothefoobarman",
  words = ["foo","bar"]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.
Example 2:

Input:
  s = "wordgoodstudentgoodword",
  words = ["word","student"]
Output: []

思路 **- 时间复杂度: O(n^2)*- 空间复杂度: O(n^2)***

这题可以动态规划的思想去解决,首先定义两个指针 i 和 j,分别指向字符串的末尾。从两个字符串的末尾开始比较,相等,则--i,--j。若不相等,有三种情况,删除 i 指向的字符,在 i 指向的字符之后增加一个字符,替换 i 指向的字符, 接着比较这三次的操作的次数,取最小值即可,不过这里要注意递归操作时会重复计算,所以我们用一个数组 dp[i][j],表示 i 在words1中的位置,j 在 words2 的位置。由于c++对动态数组的支持不是很好,这里我用 vector 代替,在效率上可能较欠缺。

class Solution {
public:
    vector<vector<int> > dp;
    int minLen(string& w1,string& w2,int i,int j)
    {
       if(i < 0)
            return j + 1;
        if(j < 0)
            return i + 1;
        if(dp[i][j])
            return dp[i][j];
        if(w1[i] == w2[j])
        {
            dp[i][j] = minLen(w1,w2,i - 1,j - 1);
            return dp[i][j];
        }
        int temp1 = min(minLen(w1,w2,i - 1,j) + 1,minLen(w1,w2,i - 1,j - 1) + 1);
        dp[i][j] = min(minLen(w1,w2,i,j - 1) + 1,temp1);
        return dp[i][j];
    }
    int minDistance(string word1, string word2) {
        int i = word1.length() - 1,j = word2.length() - 1;
        for(int t1 = 0;t1 <= i;++t1)
        {
            vector<int> v1;
            for(int t2 = 0;t2 <= j;++t2)
                v1.push_back(0);
            dp.push_back(v1);
        }
        int m = minLen(word1,word2,i,j);
        return m;
    }
};

我们一直在努力

apachecn/AiLearning

【布客】中文翻译组