Java for LeetCode 072 Edit Distance【HARD】
2015-05-17 09:53
513 查看
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 character
b) Delete a character
c) Replace a character
解题思路:
DP问题,参考思路Edit Distance@LeetCode,其中,数组我们可以用一维即可,用一个upleft表示左上的值即(dp[i-1][j-1]),JAVA实现如下:
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
解题思路:
DP问题,参考思路Edit Distance@LeetCode,其中,数组我们可以用一维即可,用一个upleft表示左上的值即(dp[i-1][j-1]),JAVA实现如下:
public int minDistance(String word1, String word2) { int[] dp = new int[word2.length() + 1]; for (int i = 0; i < dp.length; i++) dp[i] = i; for (int i = 1; i <= word1.length(); i++) { int upleft = dp[0]; dp[0] = i; for (int j = 1; j <= word2.length(); j++) { int temp = dp[j]; if (word1.charAt(i - 1) == word2.charAt(j - 1)) dp[j] = upleft; else dp[j] = Math.min(upleft, Math.min(dp[j], dp[j - 1])) + 1; upleft = temp; } } return dp[word2.length()]; }
相关文章推荐
- Java for LeetCode 146 LRU Cache 【HARD】
- Java for LeetCode 115 Distinct Subsequences【HARD】
- Java for LeetCode 126 Word Ladder II 【HARD】
- Java for LeetCode 030 Substring with Concatenation of All Words【HARD】
- Java for LeetCode 218 The Skyline Problem【HARD】
- Java for LeetCode 084 Largest Rectangle in Histogram【HARD】
- Java for LeetCode 097 Interleaving String 【HARD】
- Java for LeetCode 188 Best Time to Buy and Sell Stock IV【HARD】
- Java for LeetCode 123 Best Time to Buy and Sell Stock III【HARD】
- Java for LeetCode 078 Subsets
- Java for LeetCode 089 Gray Code
- Java for LeetCode 132 Palindrome Partitioning II
- [Leetcode] Search for a Range (Java)
- Java for LeetCode 225 Implement Stack using Queues
- Java for LeetCode 140 Word Break II
- Java for LeetCode 108 Convert Sorted Array to Binary Search Tree
- Java for LeetCode 114 Flatten Binary Tree to Linked List
- Java for LeetCode 026 Remove Duplicates from Sorted Array
- Java for LeetCode 228 Summary Ranges
- LeetCode_Number of Bits_for Java