Welcome to Subscribe On Youtube
Formatted question description: https://leetcode.ca/all/2486.html
2486. Append Characters to String to Make Subsequence
- Difficulty: Medium.
- Related Topics: Two Pointers, String, Greedy.
- Similar Questions: Is Subsequence, Minimum Operations to Make a Subsequence.
Problem
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 <= 105
-
s
andt
consist only of lowercase English letters.
Solution (Java, C++, Python)
-
class Solution { public int appendCharacters(String s, String t) { int m = s.length(), n = t.length(); for (int i = 0, j = 0; j < n; ++j) { while (i < m && s.charAt(i) != t.charAt(j)) { ++i; } if (i++ == m) { return n - j; } } return 0; } }
-
class Solution { public: int appendCharacters(string s, string t) { int m = s.size(), n = t.size(); for (int i = 0, j = 0; j < n; ++j) { while (i < m && s[i] != t[j]) { ++i; } if (i++ == m) { return n - j; } } return 0; } };
-
class Solution: def appendCharacters(self, s: str, t: str) -> int: m, n = len(s), len(t) i = 0 for j in range(n): while i < m and s[i] != t[j]: i += 1 if i == m: return n - j i += 1 return 0
-
func appendCharacters(s string, t string) int { m, n := len(s), len(t) for i, j := 0, 0; j < n; i, j = i+1, j+1 { for i < m && s[i] != t[j] { i++ } if i == m { return n - j } } return 0 }
-
function appendCharacters(s: string, t: string): number { const [m, n] = [s.length, t.length]; for (let i = 0, j = 0; j < n; ++j) { while (i < m && s[i] !== t[j]) { ++i; } if (i === m) { return n - j; } ++i; } return 0; }
Explain:
nope.
Complexity:
- Time complexity : O(n).
- Space complexity : O(n).