leetcode 583. Delete Operation for Two Strings | 583. 两个字符串的删除操作(最长公共子序列,DP)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 583. Delete Operation for Two Strings | 583. 两个字符串的删除操作(最长公共子序列,DP)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
https://leetcode.com/problems/delete-operation-for-two-strings/
題解
本題實質上是個最長公共子序列問題,又是經典的 遞歸->傻緩存->dp 得到最長公共子序列的長度 common,最后,三種方法都統一返回 s1.length() + s2.length() - 2 * common; 即可。
class Solution {// 實質上是個最長公共子序列問題public int minDistance(String s1, String s2) {// Approach 1: Recursive, Brute Force// int common = process1(s1, s2, 0, 0);// Approach 2: Recursion with Memoization// int[][] dp = new int[s1.length() + 1][s2.length() + 1];// for (int i = 0; i < s1.length(); i++) {// for (int j = 0; j < s2.length(); j++) { // 除了最后一行最后一列以外,全填初始值-1// dp[i][j] = -1;// }// }// int common = process2(s1, s2, 0, 0, dp);// Approach 3: Dynamic Programmingint[][] dp = new int[s1.length() + 1][s2.length() + 1];for (int i = 0; i < s1.length(); i++) {for (int j = 0; j < s2.length(); j++) {dp[i][j] = -1;}}for (int p1 = s1.length() - 1; p1 >= 0; p1--) {for (int p2 = s2.length() - 1; p2 >= 0; p2--) {if (s1.charAt(p1) == s2.charAt(p2)) dp[p1][p2] = 1 + dp[p1 + 1][p2 + 1];else dp[p1][p2] = Math.max(dp[p1][p2 + 1], dp[p1 + 1][p2]);}}int common = dp[0][0];return s1.length() + s2.length() - 2 * common;}// public int process1(String s1, String s2, int p1, int p2) { // if (p1 == s1.length() || p2 == s2.length()) return 0; // int res = 0; // if (s1.charAt(p1) == s2.charAt(p2)) res = 1 + process1(s1, s2, p1 + 1, p2 + 1); // else res = Math.max(process1(s1, s2, p1 + 1, p2), process1(s1, s2, p1, p2 + 1)); // return res; // }// public int process2(String s1, String s2, int p1, int p2, int[][] dp) { // if (dp[p1][p2] >= 0) return dp[p1][p2]; // int res = 0; // if (s1.charAt(p1) == s2.charAt(p2)) res = 1 + process2(s1, s2, p1 + 1, p2 + 1, dp); // else res = Math.max(process2(s1, s2, p1 + 1, p2, dp), process2(s1, s2, p1, p2 + 1, dp)); // dp[p1][p2] = res; // return dp[p1][p2]; // } }總結
以上是生活随笔為你收集整理的leetcode 583. Delete Operation for Two Strings | 583. 两个字符串的删除操作(最长公共子序列,DP)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 576. Out of
- 下一篇: leetcode 592. Fracti