给定两个字符串str1和str2以及可以对str1执行的操作。找出将“str1”转换为“str2”所需的最小编辑次数(操作)。
- 插入
- 删除
- 代替
所有上述操作具有相等的成本。
例子:
输入:str1 =“geek”,str2 =“gesek” 输出:1 我们可以通过插入一个's'将str1转换为str2。 输入:str1 =“cat”,str2 =“cut” 输出:1 我们可以通过将'a'替换为'u'来将str1转换为str2。 输入:str1 =“sunday”,str2 =“saturday” 输出:3 最后三个字符和第一个字符相同。我们基本上 需要将“un”转换为“ atur ”。这可以使用 以下三个操作来完成。 将“n”替换为“r”,插入t,插入a
这种情况下的子问题是什么?
这个想法是从两个字符串的左侧或右侧逐个处理所有字符。
让我们从右边角度穿越,对于每一对字符都有两种可能性。
m: str1(第一个字符串)的 长度n: str2(第二个字符串)的长度
- 如果两个字符串的最后字符相同,没有什么可做的。忽略最后一个字符并获取剩余字符串的计数。因此,我们重复长度m-1和n-1。
- Else(如果最后字符不相同),我们考虑对“str1”的所有操作,考虑对第一个字符串的最后一个字符的所有三个操作,递归计算所有三个操作的最小成本,并取最少三个值。
- 插入:对m和n-1重复
- 删除:重复m-1和n
- 替换:对m-1和n-1重复
下面是上面Naive递归解的Java实现。