动态规划
编辑距离
解析
- 题目中能过进行动态变化的有三种方式,插入、删除与修改一个字符。
删 m[i][j] = m[i - 1][j] + 1
改 m[i][j] = m[i - 1][j - 1] + 1
增 m[i][j] = m[i ][j - 1] + 1 - 初始状态:如果没有任意一个能过匹配则需要整个单词长度次数。
m[i][0] = i
m[0][j] = j
代码
class Solution {
public int minDistance(String word1, String word2) {
/*
a[i - 1] -> b[j - 1] k => a[i] -> b[j] k + 1
a[i - 1] -> b[j] k => a[i] -> b[j] k + 1
a[i] -> b[j - 1] k => a[i] -> b[j] k + 1
m[i][0] = i
m[0][j] = j
*/
char[] w1 = word1.toCharArray();