LeetCode: Edit Distance

来源:互联网 发布:linux系统版本选择 编辑:程序博客网 时间:2024/06/05 01:55

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:

a) Insert a character
b) Delete a character

c) Replace a character

class Solution {public:    int minDistance(string word1, string word2) {        int size1 = word1.size();        int size2 = word2.size();        int result[size1+1][size2+1];        for(int i = 0; i < size1+1; i++)        {            result[i][0] = i;        }        for(int j = 0; j < size2+1; j++)        {            result[0][j] = j;        }        for(int i = 1; i < size1+1; i++)            for(int j = 1; j < size2+1; j++)            {                if(word1[i-1] == word2[j-1])                    result[i][j] = result[i-1][j-1];                else                {                    result[i][j] = std::min(result[i-1][j-1] + 1, std::min(result[i-1][j] + 1, result[i][j-1] + 1));                }            }        return result[size1][size2];    }};

Round 2:

class Solution {public:    int minDistance(string word1, string word2) {        int steps[word1.size()+1][word2.size()+1];        for(int i = 0; i <= word1.size(); i++)        {            steps[i][0] = i;        }        for(int i = 0; i <= word2.size(); i++)        {            steps[0][i] = i;        }        for(int i = 1; i <= word1.size(); i++)            for(int j = 1; j <= word2.size(); j++)            {                steps[i][j] = std::min(std::min(steps[i-1][j], steps[i][j-1]) + 1 , steps[i-1][j-1] + (word1[i-1] == word2[j-1] ? 0 : 1));            }        return steps[word1.size()][word2.size()];            }};


0 0
原创粉丝点击