problem:
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
thinking:
(1)求全局最优解,锁定DP法
(2)DP的状态转移公式不好找,有几点是DP法共有的,可以有点启发:1、DP大都借助数组实现递推操作 2、DP法的时间复杂度:1维为O(N),2维:O(M*N)
(3)
如果我们用 i 表示当前字符串 A 的下标,j 表示当前字符串 B 的下标。 如果我们用d[i, j] 来表示A[1, ... , i] B[1, ... , j] 之间的最少编辑操作数。那末我们会有以下发现:
1. d[0, j] = j;
2. d[i, 0] = i;
3. d[i, j] = d[i⑴, j - 1] if A[i] == B[j]
4. d[i, j] = min(d[i⑴, j - 1], d[i, j - 1], d[i⑴, j]) + 1 if A[i] != B[j] //分别代表替换、插入、删除
code:
上一篇 证券-专业术语