2486. Append Characters to String to Make Subsequence
Description
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.
Constraints:
1 <= s.length, t.length <= 105sandtconsist only of lowercase English letters.
Solutions
Solution 1: Two Pointers
We define two pointers $i$ and $j$, pointing to the first characters of strings $s$ and $t$ respectively. We iterate through string $s$, if $s[i] = t[j]$, then we move $j$ one step forward. Finally, we return $n - j$, where $n$ is the length of string $t$.
The time complexity is $O(m + n)$, where $m$ and $n$ are the lengths of strings $s$ and $t$ respectively. The space complexity is $O(1)$.
Python3
class Solution:
def appendCharacters(self, s: str, t: str) -> int:
n, j = len(t), 0
for c in s:
if j < n and c == t[j]:
j += 1
return n - j
Java
class Solution {
public int appendCharacters(String s, String t) {
int n = t.length(), j = 0;
for (int i = 0; i < s.length() && j < n; ++i) {
if (s.charAt(i) == t.charAt(j)) {
++j;
}
}
return n - j;
}
}
C++
class Solution {
public:
int appendCharacters(string s, string t) {
int n = t.length(), j = 0;
for (int i = 0; i < s.size() && j < n; ++i) {
if (s[i] == t[j]) {
++j;
}
}
return n - j;
}
};
Go
func appendCharacters(s string, t string) int {
n, j := len(t), 0
for _, c := range s {
if j < n && byte(c) == t[j] {
j++
}
}
return n - j
}
TypeScript
function appendCharacters(s: string, t: string): number {
let j = 0;
for (const c of s) {
if (c === t[j]) {
++j;
}
}
return t.length - j;
}