392. Is Subsequence
Two Pointers, String, DP ·Problem Statement
link: LeetCode.cn LeetCode
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:
Input: s = "abc", t = "ahbgdc"
Output: true
Input: s = "axc", t = "ahbgdc"
Output: false
Solution Approach
The solution approach utilizes a two-pointer technique to traverse both strings simultaneously, checking for matching characters in order to determine if s is a subsequence of t.
Algorithm
- Initialize two pointers p1 and p2 to track positions in s and t, respectively.
- Iterate through both strings simultaneously, advancing pointers based on character matches.
- If p1 reaches the end of s, return True; otherwise, return False.
Implement
class Solution:
def isSubsequence(self, s, t):
p1, p2 = 0, 0
while p1 < len(s) and p2 < len(t):
if s[p1] == t[p2]:
p1 += 1
p2 += 1
if p1 < len(s):
return False
return True