FTPrep, 72 Edit Distance

来源:互联网 发布:amd显卡优化 编辑:程序博客网 时间:2024/05/21 04:22

虽然是道Hard题,但是我立马联想到了ECS124的一次HW2,回头去看了,果真是同一类型的题目,其实就是2个序列做 alignment 时,找匹配度最高的一种alignment,说到底就是DNA/protein alignment 的算法。

要看具体的2D array就去找HW2的解答,下面是代码:

class Solution {    public int minDistance(String word1, String word2) {        int len1 = word1.length();        int len2 = word2.length();        if(len1==0) return len2;        if(len2==0) return len1;        String shortWord = len1<len2?word1:word2;        String longWord = len1<len2?word2:word1;        int[] record = new int[shortWord.length()+1];        for(int i=0; i<shortWord.length()+1; i++) record[i]=i;        for(int j=0; j<longWord.length(); j++){            int[] newRecord = new int[shortWord.length()+1];            newRecord[0] = j+1; // the first elem present that the (j+1)th char in the longWord            for(int i=0; i<shortWord.length(); i++){                // newRecord[i] keep the distance between shortWord[i-1] and longWord[j], this is the difference!!                // following the above comment, to get record[i+1], we need to compare shortWord[i] and longWord[j];                if(shortWord.charAt(i)==longWord.charAt(j)) newRecord[i+1]=record[i];                 else{                    newRecord[i+1]=Math.min(newRecord[i], Math.min(record[i], record[i+1]))+1;                }            }            record=newRecord;        }        return record[shortWord.length()];    }}


之后又遇到了Interleaving String #97 这道题,思考了片刻就就觉得很想,因为要么s1要没s2的字母能够跟s3的字母匹配得上。果然是2D DP的解法。对比发现了一个关键的不同点。在Edit Distance这道题中,需要有2个record 在循环里 同时存在,因为这涉及到斜对角方向的判断,就是这一句:

if(shortWord.charAt(i)==longWord.charAt(j)) newRecord[i+1]=record[i];

而在97中间和其他的DP,比如机器人走棋盘,和有障碍的棋盘,也是用DP,但都没有需要两个array 同时存在。因为这是不需要斜对角 左上方 格子的信息。

TODO: 凡是2维DP的题,都要从最原始的解法开始,也就是robot on board这道题开始,把这4道题,都写在一起。




原创粉丝点击