編輯距離

給出兩個單詞word1和word2,計算出將word1 轉換爲word2的最少操作次數。

你總共三種操作方法:

  • 插入一個字符
  • 刪除一個字符
  • 替換一個字符
樣例

給出 work1="mart" 和 work2="karma"

返回 3

class Solution {
public:
	/**
	* @param word1 & word2: Two string.
	* @return: The minimum number of steps.
	*/
	int minDistance(string word1, string word2) {
		// write your code here
		int n = word1.length() + 1;
		int m = word2.length() + 1;
		int **arr;
		arr = new int*[n];
		for (int i = 0; i < n; i++)
		{
			arr[i] = new int[m];
		}
		for (int i = 0; i < n; i++)
			arr[i][0] = i;
		for (int j = 0; j < m; j++)
			arr[0][j] = j;

		for (int i = 1; i < n; i++)
			for (int j = 1; j < m; j++)
			{
				if (word1[i - 1] == word2[j - 1])
					arr[i][j] = arr[i - 1][j - 1];
				else
				    arr[i][j] = min
					   (arr[i - 1][j - 1] + 1,     //替換一個字符
					   arr[i][j - 1] + 1,          //插入一個字符
					   arr[i - 1][j] + 1);         //刪除一個字符
			}
		return arr[n-1][m-1];

	}

	int min(int a, int b, int c)
	{
		int temp = a > b ? b : a;
		return temp > c ? c : temp;
	}
};


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