11-1 使用關聯容器
阿新 • • 發佈:2022-02-27
動態規劃
class Solution { public int minDistance(String word1, String word2) { /** * 和《583. 兩個字串的刪除操作》一模一樣 * 只有一個地方不一樣 */ int[][] dp = new int[word1.length() + 1][word2.length() + 1]; for (int i = 0; i < word1.length() + 1; i++) { dp[i][0] = i; } for (int j = 0; j < word2.length() + 1; j++) { dp[0][j] = j; } for (int i = 1; i < word1.length() + 1; i++) { for (int j = 1; j < word2.length() + 1; j++) { if (word1.charAt(i - 1) == word2.charAt(j - 1)){ dp[i][j] = dp[i - 1][j - 1]; } /** * 如果不匹配,有三種操作 * 1、刪除:dp[i - 1][j] + 1或dp[i][j - 1] + 1 * 2、插入:等效於刪除,運算元是一樣的 * 3、修改:運算元加1,dp[i - 1][j - 1] + 1 * 最終程式碼只有這個加1不一樣 */ else { dp[i][j] = Math.min(dp[i - 1][j] + 1, Math.min(dp[i][j - 1] + 1, dp[i - 1][j - 1] + 1)); } } } return dp[word1.length()][word2.length()]; } } /** * 時間複雜度 O(n^2) * 空間複雜度 O(n^2) */