This is a creation in Article, where the information may have evolved or changed.
Topic
Problem Link: https://leetcode.com/problems/keyboard-row/#/description
Given a List of words, return the words that can is 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:
character in the keyboard more than once.
You may assume the input string would be only contain letters of alphabet.
Ideas
- Use map to store letters to the map of the row.
- Variable words, for each word, first lowercase letters are converted into Word, and then each letter of word is traversed. If the flag is the first letter, use row to store the first letter of the line, the subsequent letters, determine whether the row is equal to row, if not, directly out of the inner loop to continue to judge the next word. Considering that the array needs to be set to a predetermined length, and the array length is unknown, the entire word is determined to be saved to list, and then the elements of the list are stored in the result array.
Code
Keyboardrow.go
package _500_Keyboard_Rowimport ( "fmt" "strings")var alphabetMap map[string]intfunc 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}
Test
Keyboardrow_test.go
package _500_Keyboard_Rowimport "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")}