Leetcode Note: Go - Shortest Completing Word

Shortest Completing Word - LeetCode
https://leetcode.com/problems/shortest-completing-word/

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

所感

  • 与えられる単語のうち、最も短くなるものを return する

回答

Go Clear Solution - LeetCode Discuss
https://leetcode.com/problems/shortest-completing-word/discuss/851086/Go-Clear-Solution

func shortestCompletingWord(licensePlate string, words []string) string {
	var count int
	letters := make([]int, 26)
	for _, ch := range licensePlate {
		if ch >= 'a' && ch <= 'z' {
			letters[ch-'a']++
			count++
		}

		if ch >= 'A' && ch <= 'Z' {
			letters[ch-'A']++
			count++
		}
	}

	hasLetters := func(word string) bool {
		for ch, total := range letters {
			if total == 0 {
				continue
			}

			if strings.Count(word, string(rune(ch+'a'))) < total {
				return false
			}
		}

		return true
	}

	var word string
	for _, w := range words {
		if hasLetters(w) && (len(w) < len(word) || word == "") {
			word = w
		}

	}
	return word
}