Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions 392. Is Subsequence/392. Is Subsequence.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# 392. Is Subsequence
## STEP1
- 何も見ずに解いてみる
- 手作業でやることを実装した。
- while-else を使うことでコードは短くなるが、読みやすいかは微妙なところ。
- i, j が s, t に対応するかはなんとも言えないが、短いコードなので可とする。
```python
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
i = 0
j = 0
while i < len(s):
while j < len(t):
if s[i] == t[j]:
i += 1
j += 1
break
j += 1
else:
return False
return True
```

## STEP2
### プルリクやドキュメントを参照
- https://github.com/hayashi-ay/leetcode/pull/64/files
- STEP1 と同じ作業をとてもわかりやすく書いている。2変数あると while のネストで書こうとしてしまうのがよくない。
- 終了条件として、STEP1 のコードでは、s の末尾に到達すると break を経由して外の while を抜けるので True で終了、t の末尾まで到達して else に入ると False で終了。
- 結局これは while 文をまとめて書いて、s の末尾まで到達したかどうかで判定可能。こうすると以下のコードになる。
```python
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
i = 0
j = 0
while i < len(s) and j < len(t):
if s[i] == t[j]:
i += 1
j += 1
else:
j += 1
return i == len(s)
```
- 変形として while True で書くこともできる。
```python
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
i = 0
j = 0
while True:
if i == len(s):
return True
if j == len(t):
return False
if s[i] == t[j]:
i += 1
j += 1
else:
j += 1
```
- for 文を使うことも可
```python
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
if not s:
return True
i = 0
for character in t:
if s[i] == character:
i += 1
if i == len(s):
return True
return False
```
- https://discord.com/channels/1084280443945353267/1225849404037009609/1243290893671465080
- 変形たくさんある。

## STEP3
### 3回ミスなく書く
添字一つの方がわかりやすいと思った。
Copy link
Copy Markdown

@kzmkt kzmkt Aug 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

自分もこの形が良いかなと思いました。
2つのものを比較するときに、両方とも走らせるのは「工夫しているなぁ」と感じるので、このくらいの複雑さならこれで良いと思います

```python
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
if not s:
return True
i = 0
for character in t:
if s[i] == character:
i += 1
if i == len(s):
return True
return False
```

2分,1分,1分で3回Accept