Leetcode 2486. Append Characters to String to Make Subsequence
Intuition
Get the length of the subsequence (if any) and subtract it from the length of t to find out how many characters we have to append (if any)
Approach
Keep a count of the length of the subsequence while iterating through s and then subtract the length of the subsequence from the length of t
Code
public class Solution
{
public int AppendCharacters(string s, string t)
{ //position of the last character that forms a subsequence
int pos = 0;
//iterate through s
for(int i = 0; i < s.Length; i++)
{
//if the position of the last character that forms a
//subsequence is >= the length of t, it is already a
//subsequence so we return 0
if(pos >= t.Length)
{
return 0;
}
//otherwise we increment pos
else if(s[i] == t[pos])
{
pos++;
}
}
//once we reach the end of s we have calculated the length
//of the subsequence and can subtract it from the remaining
//characters in t so we know how many characters to append
return t.Length - pos;
}