首页 > 其他 > 详细

Edit distance

时间:2016-01-23 01:32:19      阅读:139      评论:0      收藏:0      [点我收藏+]

 

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:

  • Insert a character
  • Delete a character
  • Replace a character
Example

Given word1 = "mart" and word2 = "karma", return 3.

 

int minDistance(string word1, string word2) {
    vector<vector<int>> operates(word1.size()+1, vector<int>(word2.size()+1, 0));
    for (int i = 0; i < operates.size(); i ++) {
        operates[i][0] = i;
    }
    for (int i = 1; i < operates[0].size(); i ++) {
        operates[0][i] = i;
    }
        
    for (int r = 1; r < operates.size(); r ++) {
        for (int c = 1; c < operates[0].size(); c ++) {
            int t = word1[r-1] == word2[c-1] ? 1 : 0;
            if (t) {
                operates[r][c] = operates[r-1][c-1];
            } else {
                operates[r][c] = min(operates[r-1][c-1], min(operates[r-1][c], operates[r][c-1])) + 1;
            }
        }
    }
    
    return operates.back().back();
}

 

Edit distance

原文:http://www.cnblogs.com/whlsai/p/5152691.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!