diff --git a/392. Is Subsequence/392. Is Subsequence.md b/392. Is Subsequence/392. Is Subsequence.md new file mode 100644 index 0000000..8b540a9 --- /dev/null +++ b/392. Is Subsequence/392. Is Subsequence.md @@ -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回ミスなく書く +添字一つの方がわかりやすいと思った。 +```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