From 14d2057a8bc350eb78835b23646ee591b7fd6ca8 Mon Sep 17 00:00:00 2001 From: game-loader Date: Mon, 3 Jun 2024 21:05:07 +0800 Subject: [PATCH] leetcode update --- content/posts/leetcode.md | 50 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/content/posts/leetcode.md b/content/posts/leetcode.md index a08bafe..4f62485 100644 --- a/content/posts/leetcode.md +++ b/content/posts/leetcode.md @@ -6757,3 +6757,53 @@ func reverseString(s []byte) { } } ``` + +## day98 2024-06-03 +### 2486. Append Characters to String to Make subsequence +You are given two strings s and t consisting of only lowercase English letters. + +Return the minimum number of characters that need to be appended to the end of s so that t becomes a subsequence of s. + +A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. + +Example 1: + +Input: s = "coaching", t = "coding" +Output: 4 +Explanation: Append the characters "ding" to the end of s so that s = "coachingding". +Now, t is a subsequence of s ("coachingding"). +It can be shown that appending any 3 characters to the end of s will never make t a subsequence. + +Example 2: + +Input: s = "abcde", t = "a" +Output: 0 +Explanation: t is already a subsequence of s ("abcde"). + +Example 3: + +Input: s = "z", t = "abcde" +Output: 5 +Explanation: Append the characters "abcde" to the end of s so that s = "zabcde". +Now, t is a subsequence of s ("zabcde"). +It can be shown that appending any 4 characters to the end of s will never make t a subsequence. + +### 题解 + +本题从字符串s中删除任意位置的字符后再在末尾添加任意字符得到t, 这里从s中删除字符的位置是任意的,也就意味着只要在s中从头遍历并找到t的一个最长可行前缀即可。再用t的长度减去s中已经存在的前缀的长度级可得到需要补充的后缀长度。 + +### 代码 + +```go +func appendCharacters(s string, t string) int { + prefix := 0 + tlen := len(t) + t = t + "'" + for i,_ := range s{ + if s[i] == t[prefix]{ + prefix++ + } + } + return tlen-prefix +} +```