mirror of
https://gitlab.com/game-loader/hugo.git
synced 2025-04-20 14:02:07 +08:00
leetcode update
This commit is contained in:
parent
d8084d2a16
commit
14d2057a8b
@ -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
|
||||||
|
}
|
||||||
|
```
|
||||||
|
Loading…
Reference in New Issue
Block a user