[LeetCode] Edit Distance和Distance Subsequences

来源:互联网 发布:vmware虚拟机网络桥接 编辑:程序博客网 时间:2024/06/14 11:23

在LeetCode上遇到这两道题:Edit Distance和Distance Subsequences (详细题目请参考LeetCode),用动态规划的做法几乎是一样的。唯一的区别就是定义可用操作时,Edit Distance 有插入、替换和删除三种操作,而Distance Subsequences只有删除一种操作。程序分别如下:

Edit Distance:

两个词之间的编辑距离是NLP中常用的一种计算,在没有语义或其他先验信息的时候,可以用来度量两个单词之间的距离,《信息检索》的课程中也曾涉及,代码如下:

class Solution {public:    int minDistance(string word1, string word2) {        int w1L = word1.length();        int w2L = word2.length();                vector<vector<int> > dist(w1L+1, vector<int>(w2L+1,0));//dist[i][j]: word1[i-1]变换到word2[j-1]所需要的操作次数        for(int i=0;i<w1L+1;i++){            dist[i][0] = i;        }        for(int j=0;j<w2L+1;j++){            dist[0][j] = j;        }        for(int i=1;i<w1L+1;i++){            for(int j=1;j<w2L+1;j++){                if(word1[i-1] == word2[j-1]){                    dist[i][j] = dist[i-1][j-1];//操作次数不变                }else{                    dist[i][j] = min(min(dist[i-1][j]+1,dist[i][j-1]+1),dist[i-1][j-1]+1);//取三种操作最小值                }            }        }        return dist[w1L][w2L];    }};
Distinct Subsequences (string S中有多少不同的子序列string T):

class Solution {public:    int numDistinct(string S, string T) {        int lenS = S.length();        int lenT = T.length();                vector<vector<int> > dist(lenS+1, vector<int>(lenT+1,0));        for(int i=0;i<lenS+1;i++){            dist[i][0] = 1;        }        for(int i=1;i<lenS+1;i++){            for(int j=1;j<lenT+1;j++){                if(S[i-1] == T[j-1]){                    dist[i][j] = dist[i-1][j] + dist[i-1][j-1];//S[i-1]有两种处理方式,可以保留,也可以不保留                }else{                    dist[i][j] = dist[i-1][j];//操作次数不变                }            }        }        return dist[lenS][lenT];    }};


0 0
原创粉丝点击