-
Notifications
You must be signed in to change notification settings - Fork 0
Solved Arai60/392. Is Subsequence #56
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
| return False | ||
| last_char_index = char_index | ||
| return True | ||
| ``` |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
計算量的にはO(文字の種類*文字列の長さ)になるので状況によっては悪いですが、find がネイティブなので文字の種類が少なければ速いだろうという見積もりまであれば OK です。
| 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.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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/