500.键盘行

62 阅读1分钟

题目:
给你一个字符串数组 words ,只返回可以使用在 美式键盘 同一行的字母打印出来的单词。键盘如下图所示。
算法:

func findWords(words []string) []string {
	rowIdx := "12210111011122000010020202"
	ans := make([]string, 0)
	for i := range words {
		idx := byte('0')
		for j := range words[i] {
			index := 0
			if 'A' <= words[i][j] &&  words[i][j] <= 'Z' {
				index = int(words[i][j] - 'A')
			} else {
				index = int(words[i][j] - 'a')
			}
			if j > 0 && rowIdx[index] != idx {
				goto Next
			}
			idx = rowIdx[index]
		}
		ans = append(ans, words[i])
		Next:
	}
	return ans
}