Conversation
| return False | ||
| last_char_index = char_index | ||
| return True | ||
| ``` |
There was a problem hiding this comment.
last_char_index と char_index が少し把握しにくかったです。char_index はあるループで一致する文字が見つかったかを判定するために使われていると思います。
フラグ的にするか
def isSubsequence(self, s: str, t: str) -> bool:
last_char_index = 0
for c in s:
char_index = last_char_index
for i in range(last_char_index, len(t)):
if c == t[i]:
last_char_index = i + 1
break
if last_char_index == char_index:
return False
return Truefor-else を使うことも可能かと思いました。
def isSubsequence(self, s: str, t: str) -> bool:
search_start_index = 0
for c in s:
for i in range(search_start_index, len(t)):
if c == t[i]:
search_start_index = i + 1
break
else:
return False
return True|
|
||
| ## Step 3. Final Solution | ||
|
|
||
| - 自分で最初に書いたやり方がしっくり来ていたのでちょっとだけ変えて練習 |
There was a problem hiding this comment.
計算量的にはO(文字の種類*文字列の長さ)になるので状況によっては悪いですが、find がネイティブなので文字の種類が少なければ速いだろうという見積もりまであれば OK です。
There was a problem hiding this comment.
計算量的にはO(文字の種類*文字列の長さ)になる
文字の種類はどこから出てくるのでしょうか?
str.find() にバインドされている実装のエントリポイントはここだと思っていて:
https://github.com/python/cpython/blob/v3.14.3/Objects/unicodeobject.c#L11958
クエリ文字の長さが1なのでここに当たり:
https://github.com/python/cpython/blob/v3.14.3/Objects/unicodeobject.c#L9696-L9704
find_char の実装を読む感じ、memchr を使ったスキャン、あるいは文字一致&線形探索になるように見えるのですが
https://github.com/python/cpython/blob/v3.14.3/Objects/stringlib/fastsearch.h#L50
There was a problem hiding this comment.
文字の種類ではなく、sの長さの書き間違えっぽいですね。for ch in sのところを指しているかと。
| char_index = 0 | ||
| for c in s: | ||
| char_index = t.find(c, char_index) + 1 | ||
| if char_index == 0: |
There was a problem hiding this comment.
find() から -1 が返ってきたときに、 t.find(c, char_index) + 1 が 0 になるから return False するというのは、ややパズルに感じました。
char_index = t.find(c, char_inde)
if char_index == -1:
return False
char_index += 1のほうが分かりやすいと思います。
問題文:https://leetcode.com/problems/is-subsequence/description/