Leetcode Note: Go - Check if a Word Occurs as a Prefix of Any Word in a Sentence

Check If a Word Occurs As a Prefix of Any Word in a Sentence - LeetCode
https://leetcode.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/

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

回答

Go without strings package - Check If a Word Occurs As a Prefix of Any Word in a Sentence - LeetCode
https://leetcode.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/solutions/773843/go-without-strings-package/

func isPrefixOfWord(sentence string, searchWord string) int {
	if len(sentence) < len(searchWord) {
		return -1
	}

	if sentence[:len(searchWord)] == searchWord {
		return 1
	}

	count := 1
	for i := 1; i < len(sentence)-len(searchWord); i++ {
		if sentence[i] != ' ' {
			continue
		}

		count++
        i++
		if sentence[i:i+len(searchWord)] == searchWord {
			return count
		}
	}

	return -1
}