Back to Leetcode Go

500. Keyboard Row

website/content.en/ChapterFour/0500~0599/0500.Keyboard-Row.md

1.7.971.4 KB
Original Source

500. Keyboard Row

Problem

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:

Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]

Note:

  1. You may use one character in the keyboard more than once.
  2. You may assume the input string will only contain letters of alphabet.

Problem Summary

Given a list of words, return only the words that can be typed using letters from the same row of the keyboard. The keyboard is as shown in the image above.

Solution Approach

  • Given a string array, determine in order whether each string in the array is located entirely on the same row of the keyboard; if so, output it. This is also an easy problem.

Code

go

package leetcode

import "strings"

func findWords500(words []string) []string {
	rows := []string{"qwertyuiop", "asdfghjkl", "zxcvbnm"}
	output := make([]string, 0)
	for _, s := range words {
		if len(s) == 0 {
			continue
		}
		lowerS := strings.ToLower(s)
		oneRow := false
		for _, r := range rows {
			if strings.ContainsAny(lowerS, r) {
				oneRow = !oneRow
				if !oneRow {
					break
				}
			}
		}
		if oneRow {
			output = append(output, s)
		}
	}
	return output
}