Skip to content

2486. Append Characters to String to Make Subsequence 👍

  • Time: $O(|\texttt{s}|)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
 public:
  int appendCharacters(string s, string t) {
    int i = 0;  // t's index

    for (const char c : s)
      if (c == t[i])
        if (++i == t.length())
          return 0;

    return t.length() - i;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
  public int appendCharacters(String s, String t) {
    int i = 0; // t's index

    for (final char c : s.toCharArray())
      if (c == t.charAt(i))
        if (++i == t.length())
          return 0;

    return t.length() - i;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def appendCharacters(self, s: str, t: str) -> int:
    i = 0  # t's index

    for c in s:
      if c == t[i]:
        i += 1
        if i == len(t):
          return 0

    return len(t) - i