1. 程式人生 > 其它 >C++ 子串匹配主串

C++ 子串匹配主串

動態規劃

class Solution {
    public int minDistance(String word1, String word2) {

        /**
         * dp[i][j]定義為以word1[i - 1]結尾的字串,和以word2[j - 1]結尾的字串,要想相等需要刪除的最小元素個數
         * 當一個為空時,就只能刪除另一個字串中的所有元素
         */
        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、只刪除word1[i - 1]
                 * 2、只刪除word2[j - 1]
                 * 3、同時刪除word1[i - 1]和word2[j - 1]
                 */
                else {
                    dp[i][j] = Math.min(dp[i - 1][j] + 1, Math.min(dp[i][j - 1] + 1, dp[i - 1][j - 1] + 2));
                }
            }
        }

        return dp[word1.length()][word2.length()];
    }
}

/**
 * 時間複雜度 O(n^2)
 * 空間複雜度 O(n^2)
 */

《1143. 最長公共子序列》改編

class Solution {
    public int minDistance(String word1, String word2) {

        /**
         * 先求出最長公共子串,然後用word1和word2的總長度減去兩倍公共長度,就是二者刪除的元素個數
         */
        int[][] dp = new int[word1.length() + 1][word2.length() + 1];

        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;
                }
                else {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        
        return word1.length() + word2.length() - 2 * dp[word1.length()][word2.length()];
    }
}

/**
 * 時間複雜度 O(n^2)
 * 空間複雜度 O(n^2)
 */

https://leetcode-cn.com/problems/delete-operation-for-two-strings/