The sub-problem of edit distance is the edit distance of string A[0:i] and string B[0:j].
The boundary cases are:
A.length() == 0, then edit distance isB.legnth()B.length() == 0, then edit distance isA.length()- otherwise, there are three cases (log the minimum score):
- if we align
AandBatiandjrespectly, then the edit distance isM[i-1][j-1] + (A[i] == B[j] ? 0 : 1) - if we align by
A[0:i-1]andB[0:j], then we need to perform a delete/add operation - if we align by
A[0:i]andB[0:j-1], then we need to perform a delete/add operation
- if we align
By analysis the above conditions, we can know the state we need to keep is two rows, namely M[i-1][0:j] and M[i][0:j].
Therefore, the code is: