LeetCode:Edit Distance

Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2.(each operation is counted as 1step.)

You have the following 3 operations permitted on word:

1、Insert a character

2、Delete a character

3、Replace a character

解題思路:
使用動態規劃的思想,設狀態爲f[i][j] , 表示A[0, i] 和 B[0, j] 之間的最小編輯距離。 設A[0, i] 的形式是str1c, B[0,j] 的形式爲str2d,

1、如果c==d,則f[i][j] = f[i-1][j-1];

2、如果c!=d,

a) 如果將c替換成d, 則f[i][j] = f[i-1][j-1] + 1;

b)如果在c後面添加一個d,則f[i][j] = f[i][j-1] + 1;

c)如果將c刪除,則f[i][j] = f[i-1][j] + 1;

代碼如下:

class Solution {
public:
    int minDistance(string word1, string word2) {
    	int n = word1.size();
    	int m = word2.size();
    	int f[n+1][m+1];
    	for(auto i=0; i<=n; i++) {
    		f[i][0] = i;
    	}
    	for(auto j=0; j<=m; j++) {
    		f[0][j] = j;
    	}
    	for(auto i=1; i<=n; i++) {
    		for(auto j=1; j<=m; j++) {
    			if(word1[i-1] == word2[j-1]) {
    				f[i][j] = f[i-1][j-1];
    			} else {
    				int mn = min(f[i-1][j], f[i][j-1]);
    				f[i][j] = 1 + min(f[i-1][j-1], mn);
    			}
    		}
    	}
    	return f[n][m];
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章