Skip to content

392. Is Subsequence 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  bool isSubsequence(string s, string t) {
    if (s.empty())
      return true;

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

    return false;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public boolean isSubsequence(String s, String t) {
    if (s.isEmpty())
      return true;

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

    return false;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def isSubsequence(self, s: str, t: str) -> bool:
    if not s:
      return True

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

    return False