Leetcode Note: Go - Check If Two String Arrays are Equivalent

Check If Two String Arrays are Equivalent - LeetCode
https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/

  • Go 言語で取り組んだメモ

回答

[golang] constant space solution using iterators - Check If Two String Arrays are Equivalent - LeetCode
https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/solutions/945285/golang-constant-space-solution-using-iterators/

func arrayStringsAreEqual(word1 []string, word2 []string) bool {
    it1, it2 := iterator{words:word1}, iterator{words:word2}
    for it1.hasNext() && it2.hasNext() {
        if it1.next() != it2.next() {
            return false
        }
    }
    return it1.hasNext() == it2.hasNext()
}

type iterator struct {
    words []string
    currentWord int
    currentIndex int
}

func (i *iterator) hasNext() bool {
    if i.currentWord < len(i.words) {
        if i.currentIndex < len(i.words[i.currentWord]) {
            return true
        } else {
            i.currentWord++
            i.currentIndex = 0
            return i.hasNext()
        }
    }
    return false
}

func (i *iterator) next() byte {
    var result byte
    if !i.hasNext() {
        return result
    }
    result = i.words[i.currentWord][i.currentIndex]
    i.currentIndex++
    return result
}