👩‍💻 리트 코드

[LeetCode] 392. Is Subsequence

MINAIR 2025. 3. 20. 00:26

Problem


Given two strings s and t, return true if s is a subsequence of t, or false otherwise.

A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).

 

Example 1:

Input: s = "abc", t = "ahbgdc"
Output: true

Example 2:

Input: s = "axc", t = "ahbgdc"
Output: false

 

Constraints:

  • 0 <= s.length <= 100
  • 0 <= t.length <= 104
  • s and t consist only of lowercase English letters.

Solution


먼저 output을 빈 문자열로 초기화, s를 for문으로 돌고, t를 pointer를 이용해 가리킨다. 만약 s와 t에서 같은 문자가 있으면 output에 그 문자를 추가하고 pointer를 한 칸 전진시킨다. 같은 문자가 나올 때까지 or t 문자열이 끝날 때까지 pointer를 전진시키며 같은 문자가 있는지 확인한다. 최종적으로 output과 s가 같은지 확인하여 true와 false를 반환한다. 

 

class Solution:
    def isSubsequence(self, s: str, t: str) -> bool:
        pointer = 0
        output = ""
        for c in s:
            while pointer < len(t):
                if c == t[pointer]:
                    output += c
                    pointer += 1
                    break
                pointer += 1
        return s == output