mirror of
https://github.com/prdlk/leetcode.git
synced 2026-11-02 13:12:44 +00:00
72 lines
1.9 KiB
Plaintext
72 lines
1.9 KiB
Plaintext
---
|
|
title: '392. Is Subsequence'
|
|
description: Given two strings s and t, return true if s is a subsequence of t, or false otherwise
|
|
icon: dot
|
|
topics:
|
|
- { name: "Two Pointers", slug: "two-pointers" }
|
|
- { name: "String", slug: "string" }
|
|
- { name: "Dynamic Programming", slug: "dynamic-programming" }
|
|
video: "99RVfqklbCE"
|
|
issue: "https://github.com/prdlk/leetcode/issues/45"
|
|
companies:
|
|
- { name: "Amazon", period: "Three Months", frequency: 34.6 }
|
|
- { name: "Bloomberg", period: "Six Months", frequency: 25.5 }
|
|
- { name: "Google", period: "Six Months", frequency: 25.4 }
|
|
- { name: "Meta", period: "Six Months", frequency: 24.5 }
|
|
- { name: "Microsoft", period: "Six Months", frequency: 24.1 }
|
|
sidebar:
|
|
label: 'Is Subsequence'
|
|
badge: 'Easy'
|
|
---
|
|
|
|
::::warning
|
|
Suppose there are lots of incoming s, say s1, s2, ..., sk where k >= 10^9, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code?
|
|
::::
|
|
|
|
### 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 <= 10^4`
|
|
- `s` and `t` consist only of lowercase English letters.
|
|
|
|
## Approach
|
|
|
|
```mermaid
|
|
flowchart TD
|
|
S(["isSubsequence(s, t)"]) --> G{"len(s) > len(t)?"}
|
|
G -- yes --> X(["return False"])
|
|
G -- no --> I["i = 0 into s, j = 0 into t"]
|
|
I --> W{"i < len(s) and j < len(t)?"}
|
|
W -- no --> E(["return i == len(s) — every char of s was matched"])
|
|
W -- yes --> Q{"s[i] == t[j]?"}
|
|
Q -- yes --> A["i += 1 — consume the match"]
|
|
Q -- no --> B["j += 1 — always advance t"]
|
|
A --> B
|
|
B --> W
|
|
```
|
|
|
|
## Solution
|
|
|
|
```py
|
|
class Solution:
|
|
def isSubsequence(self, s: str, t: str) -> bool:
|
|
if len(s) > len(t):
|
|
return False
|
|
|
|
i, j = 0, 0
|
|
while i < len(s) and j < len(t):
|
|
if s[i] == t[j]:
|
|
i += 1
|
|
j += 1
|
|
|
|
return i == len(s)
|
|
```
|