摘要:構(gòu)造數(shù)組,是的,是的,是將位的轉(zhuǎn)換成位的需要的步數(shù)。初始化和為到它們各自的距離,然后兩次循環(huán)和即可。
Problem
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:
Insert a character
Delete a character
Replace a character
Given word1 = "mart" and word2 = "karma", return 3.
Note構(gòu)造dp[i][j]數(shù)組,i是word1的index+1,j是word2的index+1,dp[i][j]是將i位的word1轉(zhuǎn)換成j位的word2需要的步數(shù)。初始化dp[i][0]和dp[0][i]為dp[0][0]到它們各自的距離i,然后兩次循環(huán)i和j即可。
理解三種操作:insertion是完成i-->j-1之后,再插入一位才完成i-->j;deletion是完成i-->j之后,發(fā)現(xiàn)i多了一位,所以i-1-->j才是所求,需要再刪除一位才完成i-->j;而replacement則是換掉word1的最后一位,即之前的i-1-->j-1已經(jīng)完成,如果word1的第i-1位和word2的第j-1位相等,則不需要替換操作,否則要替換一次完成i-->j。
public class Solution { public int minDistance(String word1, String word2) { int m = word1.length(), n = word2.length(); int[][] dp = new int[m+1][n+1]; for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0) dp[i][j] = j; else if (j == 0) dp[i][j] = i; else { int insert = dp[i][j-1] + 1; int delete = dp[i-1][j] + 1; int replace = dp[i-1][j-1] + (word1.charAt(i-1) == word2.charAt(j-1) ? 0 : 1); dp[i][j] = Math.min(insert, Math.min(delete, replace)); } } } return dp[m][n]; } }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://specialneedsforspecialkids.com/yun/65798.html
Problem A group of two or more people wants to meet and minimize the total travel distance. You are given a 2D grid of values 0 or 1, where each 1 marks the home of someone in the group. The distance ...
摘要:建立動(dòng)規(guī)數(shù)組,表示從起點(diǎn)處到達(dá)該點(diǎn)的可能性。循環(huán)結(jié)束后,數(shù)組對(duì)所有點(diǎn)作為終點(diǎn)的可能性都進(jìn)行了賦值。和的不同在于找到最少的步數(shù)。此時(shí)的一定是滿(mǎn)足條件的最小的,所以一定是最優(yōu)解。 Jump Game Problem Given an array of non-negative integers, you are initially positioned at the first index...
摘要:比較長(zhǎng)度法復(fù)雜度時(shí)間空間思路雖然我們可以用的解法,看是否為,但中會(huì)超時(shí)。這里我們可以利用只有一個(gè)不同的特點(diǎn)在時(shí)間內(nèi)完成。 One Edit Distance Given two strings S and T, determine if they are both one edit distance apart. 比較長(zhǎng)度法 復(fù)雜度 時(shí)間 O(N) 空間 O(1) 思路 雖然我們可以用...
摘要:復(fù)雜度思路考慮如果兩個(gè)字符串的長(zhǎng)度,是肯定當(dāng)兩個(gè)字符串中有不同的字符出現(xiàn)的時(shí)候,說(shuō)明之后的字符串一定要相等。的長(zhǎng)度比較大的時(shí)候,說(shuō)明的時(shí)候,才能保證距離為。 LeetCode[161] One Edit Distance Given two strings S and T, determine if they are both one edit distance apart. Stri...
摘要:復(fù)雜度思路考慮用二維來(lái)表示變換的情況。如果兩個(gè)字符串中的字符相等,那么如果兩個(gè)字符串中的字符不相等,那么考慮不同的情況表示的是,從字符串到的位置轉(zhuǎn)換到字符串到的位置,所需要的最少步數(shù)。 LeetCode[72] Edit Distance Given two words word1 and word2, find the minimum number of steps require...
閱讀 2752·2021-11-24 10:23
閱讀 1159·2021-11-17 09:33
閱讀 2507·2021-09-28 09:41
閱讀 1418·2021-09-22 15:55
閱讀 3644·2019-08-29 16:32
閱讀 1911·2019-08-29 16:25
閱讀 1060·2019-08-29 11:06
閱讀 3427·2019-08-29 10:55