题目
问题链接:https://leetcode.com/problems/keyboard-row/#/description
Given a List of words, return the words that can be typed using letters of alphabet on only one row’s of American keyboard like the image below.
Example 1:
Input: ["Hello", "Alaska", "Dad", "Peace"]Output: ["Alaska", "Dad"]
Note:
You may use one character in the keyboard more than once.
You may assume the input string will only contain letters of alphabet.
思路
- 用Map存储字母到所在行的映射。
- 变量words,对每一个单词,先做小写字母转换存入word,再对word的每个字母进行遍历。用flag标记是否是第一个字母,用row存储第一个字母所在的行,对后续的字母,判断其所在行是否等于row,若不是,直接跳出内层循环继续判断下一个单词。考虑到数组需要预先设置长度,而数组长度未知,所以判断整个单词完毕后将其县存入List,最后再把List的元素存入结果数组。
代码
keyboardRow.go
package _500_Keyboard_Row
import (
"fmt"
"strings"
)
var alphabetMap map[string]int
func init() {
alphabetMap = make(map[string]int)
row1 := []string{"q", "w", "e", "r", "t", "y", "u", "i", "o", "p"}
row2 := []string{"a", "s", "d", "f", "g", "h", "j", "k", "l"}
for _, v := range row1 {
alphabetMap[v] = 1
}
for _, v := range row2 {
alphabetMap[v] = 2
}
}
func findWord(word string) (ret bool) {
word = strings.ToLower(word)
var allRow int
allRow = alphabetMap[word[:1]]
length := len(word)
for i := 1; i < length; i++ {
row := alphabetMap[word[i:i+1]]
if allRow != row {
return false
}
}
return true
}
func FindWords(words []string) []string {
var ret []string
for _, v := range words {
ok := findWord(v)
if ok {
ret = append(ret, v)
}
}
fmt.Printf("ret:%+v\n", ret)
return ret
}
测试
keyboardRow_test.go
package _500_Keyboard_Row
import "testing"
func TestFindWords(t *testing.T) {
words := []string{
"Hello", "Alaska", "Dad", "Peace"}
ret := FindWords(words)
wanted := map[string]int{
"Alaska": 1,
"Dad": 2,
}
for _, v := range ret {
_, ok := wanted[v]
if !ok {
t.Errorf("fail, not want but have %+v\n", v)
return
}
}
t.Logf("pass")
}
有疑问加站长微信联系(非本文作者)