【LeetCode】72.Edit Distance解题报告

来源:互联网 发布:mac优酷 编辑:程序博客网 时间:2024/06/04 20:01

【LeetCode】72.Edit Distance解题报告

tags: DP String

题目地址:https://leetcode.com/problems/edit-distance/description/
题目描述:

  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 characterb) Delete a characterc) Replace a character

Solutions:

class Solution {    public int minDistance(String word1, String word2) {        int[][] dp = new int[word1.length()+1][word2.length()+1];        for(int i = 0; i <= word1.length() ; i++){            dp[i][0] = i;        }        for(int i = 0; i<=word2.length() ; i++){            dp[0][i] = i;        }        for(int i = 1 ;i<=word1.length();i++){            for(int j = 1 ; j<=word2.length() ; j++){                if(word1.charAt(i-1) == word2.charAt(j-1)){                    dp[i][j] = dp[i-1][j-1];                }else{                    dp[i][j] = dp[i-1][j-1] + 1;   //replace operation                }                dp[i][j] = Math.min(dp[i][j],Math.min(dp[i][j-1]+1,dp[i-1][j]+1));            }        }        return dp[word1.length()][word2.length()];    }}

  此类String问题,有一个可用的模板。如下:

two conditions满足dp的两个条件1.optimal substructure最优子结构2.overlap subproblems重复子问题1->2:  0->1 replace       0->2 remove       1->1 insertdp[i][j]:min steps to convert word1 to word2 with length jthree steps:1.base case2.update function3.goala->b:""->b + removea -> "" +insertdp[i][j]dp[i-1][j-1]:previous operationdp[i-1][j]dp[i][j-1]

Date:2017年10月22日

原创粉丝点击