LeetCode, leetcodeoj

Source: Internet
Author: User

LeetCode, leetcodeoj

Question:

Given two wordsWord1AndWord2, Find the minimum number of steps required to convertWord1ToWord2. (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

Ideas:

Dynamic Planning, dp (I, j) refers to the number of transformations required for the (I-1) and (J-1) locations to be equal if word1 [I-1] = word2 [J-1], so dp (I, j) = dp (I-1, J-1), otherwise, it is from dp (I-1, J-1), dp (I, J-1), dp (I-1, j), select a minimum value, and then add 1.

package dp;public class EditDistance {    public int minDistance(String word1, String word2) {        int m = word1.length();        int n = word2.length();        int[][] dp = new int[m + 1][n + 1];        for (int i = 0 ;i <= m ; ++i)            dp[i][0] = i;        for (int i = 0; i <= n; ++i)            dp[0][i] = i;        for (int i = 1; i <= m; ++i) {            for (int j = 1; j <= n; ++j) {                if (word1.charAt(i - 1) == word2.charAt(j - 1)) {                     dp[i][j] = dp[i - 1][j - 1];                } else {                    dp[i][j] = 1 + Math.min(Math.min(dp[i - 1][j - 1], dp[i][j - 1]), dp[i - 1][j]);                }            }        }                return dp[m][n];    }        public static void main(String[] args) {        // TODO Auto-generated method stub        EditDistance e = new EditDistance();        System.out.println(e.minDistance("a", "b"));        System.out.println(e.minDistance("abc", "bc"));        System.out.println(e.minDistance("abc", "def"));        System.out.println(e.minDistance("abcdefg", "bcdefgh"));        System.out.println(e.minDistance("abc", "cba"));            }}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.