Skip to content

3135. Equalize Strings by Adding or Removing Characters at Ends 👍

  • Time: $O(mn)$
  • Space: $O(mn)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  int minOperations(string initial, string target) {
    const int m = initial.length();
    const int n = target.length();
    // dp[i][j] := the length of LCS(initial[0..i), target[0..j))
    vector<vector<int>> dp(m + 1, vector<int>(n + 1));

    for (int i = 1; i <= m; ++i)
      for (int j = 1; j <= n; ++j)
        if (initial[i - 1] == target[j - 1])
          dp[i][j] = 1 + dp[i - 1][j - 1];

    const int maxCommonLength = accumulate(
        dp.begin(), dp.end(), 0, [](int subtotal, const vector<int>& row) {
      return max(subtotal, ranges::max(row));
    });
    return m + n - 2 * maxCommonLength;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int minOperations(String initial, String target) {
    final int m = initial.length();
    final int n = target.length();
    // dp[i][j] := the length of LCS(initial[0..i), target[0..j))
    int[][] dp = new int[m + 1][n + 1];

    for (int i = 1; i <= m; ++i)
      for (int j = 1; j <= n; ++j)
        if (initial.charAt(i - 1) == target.charAt(j - 1))
          dp[i][j] = 1 + dp[i - 1][j - 1];

    final int maxCommonLength = Arrays.stream(dp).flatMapToInt(Arrays::stream).max().getAsInt();
    return m + n - 2 * maxCommonLength;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def minOperations(self, initial: str, target: str) -> int:
    m = len(initial)
    n = len(target)
    # dp[i][j] := the length of LCS(initial[0..i), target[0..j))
    dp = [[0] * (n + 1) for _ in range(m + 1)]

    for i in range(1, m + 1):
      for j in range(1, n + 1):
        if initial[i - 1] == target[j - 1]:
          dp[i][j] = 1 + dp[i - 1][j - 1]

    return m + n - 2 * max(map(max, dp))