内容中心

2026年靠谱的江苏大型制氮机高口碑品牌推荐-苏州希特高纯气体设备有限公司

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

  1. 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).
  2. Minimal Insertions: The number of insertions needed to make t a subsequence of s is the length of t minus the length of the LCS of s and t. This is because the LCS represents the part of t that is already a subsequence of s, so the remaining characters in t need to be inserted into s.

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

  1. Initialization: We start with a prev array of size len(t)+1 initialized to zero. This array keeps track of the LCS length up to the previous character in s.
  2. Iterate Over s: For each character in s, we compute a curr array that tracks the LCS length up to the current character in s.
  3. Compute LCS: For each character in t, if it matches the current character in s, we update curr[j] to be prev[j-1] + 1 (since we extend the LCS by one). Otherwise, curr[j] is the maximum of prev[j] (LCS without current character in s) or curr[j-1] (LCS without current character in t).
  4. Track Maximum LCS: We keep track of the maximum value in the curr array to get the length of the LCS of s and t.
  5. 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.

苏州希特高纯气体设备有限公司

苏州希特高纯气体设备有限公司



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

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?