To solve this problem, we need to determine the minimum number of insertions required to make string t a subsequence of string s. The key insight here is to use the Longest Common Subsequence (LCS) between s and t to find the answer. The minimal number of insertions needed is the difference between the length of t and the length of the LCS of s and t.
Approach
- Longest Common Subsequence (LCS): The LCS of two strings is the longest sequence of characters that appear in both strings in the same relative order (but not necessarily contiguously).
- Minimal Insertions: The number of insertions needed to make
ta subsequence ofsis the length oftminus the length of the LCS ofsandt. This is because the LCS represents the part oftthat is already a subsequence ofs, so the remaining characters intneed to be inserted intos.
Solution Code
def min_insertions_to_make_subsequence(s: str, t: str) -> int:
m = len(t)
prev = [0] * (m + 1)
max_lcs = 0
for c in s:
curr = [0] * (m + 1)
for j in range(1, m + 1):
if c == t[j-1]:
curr[j] = prev[j-1] + 1
else:
curr[j] = max(prev[j], curr[j-1])
if curr[j] > max_lcs:
max_lcs = curr[j]
prev = curr
return len(t) - max_lcs
# Example usage:
# s = "abcde"
# t = "aec"
# print(min_insertions_to_make_subsequence(s, t)) # Output: 1
Explanation
- Initialization: We start with a
prevarray of sizelen(t)+1initialized to zero. This array keeps track of the LCS length up to the previous character ins. - Iterate Over
s: For each character ins, we compute acurrarray that tracks the LCS length up to the current character ins. - Compute LCS: For each character in
t, if it matches the current character ins, we updatecurr[j]to beprev[j-1] + 1(since we extend the LCS by one). Otherwise,curr[j]is the maximum ofprev[j](LCS without current character ins) orcurr[j-1](LCS without current character int). - Track Maximum LCS: We keep track of the maximum value in the
currarray to get the length of the LCS ofsandt. - Calculate Insertions: The minimal insertions needed is
len(t) - max_lcs.
This approach efficiently computes the required result with a time complexity of O(n*m) (where n is the length of s and m is the length of t) and space complexity of O(m) (since we only use two arrays of size m+1). This makes it suitable for most practical cases.


作者声明:本文包含人工智能生成内容。