Skip to content

Conversation

@hroc135
Copy link
Owner

@hroc135 hroc135 commented Apr 22, 2025

- ただし、unicode に対応しようとすると、rune 型のスライスを作らないといけないので空間計算量が O(s+t) になってしまう

#### 2c
- https://github.com/fhiyo/leetcode/pull/55/files#diff-a6c7d5ff748fd033529b0b0a550ed2aa570e18edc3e2c61da5094aec0e23a91eR55
Copy link

Choose a reason for hiding this comment

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

この方法、二分探索せずに、線形で探索して頭から捨てていけば、O(n) で終わりそうですね。Go だとスライスの操作になりますかね。

Copy link
Owner Author

Choose a reason for hiding this comment

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

なるほどです。slices.IndexFunc を使って書いてみました。
ちょっとわかりにくいコードになった気がするのでコメントを書いたほうがいいかなと思いました。

func isSubsequence(s string, t string) bool {
    tCharToIndices := make(map[rune][]int)
    for i, tc := range t {
        tCharToIndices[tc] = append(tCharToIndices[tc], i)
    }
    tIndex := -1
    for _, sc := range s {
        tIndices, found := tCharToIndices[sc]
        if !found {
            return false
        }
        ti := slices.IndexFunc(tIndices, func(a int) bool { return a > tIndex })
        if ti < 0 {
            return false
        }
        tIndex = tCharToIndices[sc][ti]
        tCharToIndices[sc] = tCharToIndices[sc][ti+1:]
    }
    return true
}

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.

3 participants