[LeetCode] 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.

Constraints:
1 <= s.length, t.length <= 105
s and t consist only of lowercase English letters.

追加字符以获得子序列。

给你两个仅由小写英文字母组成的字符串 s 和 t 。

现在需要通过向 s 末尾追加字符的方式使 t 变成 s 的一个 子序列 ,返回需要追加的最少字符数。

子序列是一个可以由其他字符串删除部分(或不删除)字符但不改变剩下字符顺序得到的字符串。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/append-characters-to-string-to-make-subsequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

思路是双指针。这是判断子序列的基本题,我们用两个指针 i, j 分别指向 s 和 t (长度分别为 m 和 n)并同时开始遍历。如果 t 先遍历完,说明 t 本身就是 s 的子序列;如果 s 遍历完之后发现 t 还未遍历完,那么 s 需要补足的字符个数 = n - j,即 t 中还未遍历到的字符个数。

复杂度

时间O(m) - s 的长度
空间O(1)

代码

Java实现

class Solution {
    public int appendCharacters(String s, String t) {
        int m = s.length();
        int n = t.length();
        int i = 0;
        int j = 0;
        while (i < m && j < n) {
            if (s.charAt(i) == t.charAt(j)) {
                j++;
            }
            i++;
        }
        if (j == n) {
            return 0;
        }
        return n - j;
    }
}
posted @ 2023-07-19 22:23  CNoodle  阅读(56)  评论(0编辑  收藏  举报