Problem Summary
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:
(1) Insert a character
(2) Delete a character
(3) Replace a character
Solution
We can solve this problem with dynamic programming.
Suppose we are going to convert S[0…N] to T[0…M] and we take all operations from left to right, with the minimal number of steps being f[N][M].
If S[N] == T[M], f[N][M] = f[N-1][M-1]. Otherwise, we have three cases:
Convert S[0…N] to T[0…M-1], then insert T[M] to the end of S. This will cost f[N][M-1] + 1.
Convert S[0…N-1] to T[0…M], then delete S[N]. This will cost f[N-1][M] + 1.
Convert S[0…N-1] to T[0…M-1], then replace S[N] with T[M]. This will cost f[N-1][M-1] + 1.
Code 1: O(N*M) space
|
|
Code 2: O(M) space
|
|