Leetcode Note: Go - Keyboard Row

Keyboard Row - LeetCode
https://leetcode.com/problems/keyboard-row/

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

所感

  • words 配列を US 配列のアルファベット列で入力できる単語を return

回答

[Go] Easy solution - LeetCode Discuss
https://leetcode.com/problems/keyboard-row/discuss/556691/Go-Easy-solution

func findWords(words []string) []string {
	lineOne := map[rune]struct{}{
		'q': {},
		'w': {},
		'e': {},
		'r': {},
		't': {},
		'y': {},
		'u': {},
		'i': {},
		'o': {},
		'p': {},
	}
	lineTwo := map[rune]struct{}{
		'a': {},
		's': {},
		'd': {},
		'f': {},
		'g': {},
		'h': {},
		'j': {},
		'k': {},
		'l': {},
	}
	lineThree := map[rune]struct{}{
		'z': {},
		'x': {},
		'c': {},
		'v': {},
		'b': {},
		'n': {},
		'm': {},
	}

	result := []string{}
	for _, word := range words {
		var line map[rune]struct{}

		if _, ok := lineOne[unicode.ToLower(rune(word[0]))]; ok {
			line = lineOne
		} else if _, ok := lineTwo[unicode.ToLower(rune(word[0]))]; ok {
			line = lineTwo
		} else {
			line = lineThree
		}

		good := true
		for _, r := range word {
			if _, ok := line[unicode.ToLower(r)]; !ok {
				good = false
				break
			}
		}

		if good {
			result = append(result, word)
		}
	}

	return result
}