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
'👩💻 리트 코드' 카테고리의 다른 글
[LeetCode] 1732. Find the Highest Altitude (0) | 2025.03.24 |
---|---|
[LeetCode] 2215. Find the Difference of Two Array (0) | 2025.03.21 |
[LeetCode] 1071. Greatest Common Divisor of Strings (0) | 2025.03.17 |
[LeetCode] 643. Maximum Average Subarray1 (0) | 2025.03.14 |
[LeetCode 75] 283. Move Zeros (0) | 2025.03.12 |