Skip to content

Conversation

@Satorien
Copy link
Owner

@Satorien Satorien commented Jan 4, 2026

return False
last_char_index = char_index
return True
```

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 True

for-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

- 自分で最初に書いたやり方がしっくり来ていたのでちょっとだけ変えて練習
Copy link

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:
Copy link

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

のほうが分かりやすいと思います。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants