Skip to content
On this page

500. 键盘行

原题链接:LeetCode 500. 键盘行

题目描述

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

请注意,字符串 不区分大小写,相同字母的大小写形式都被视为在同一行**。**

美式键盘 中:

- 第一行由字符 `"qwertyuiop"` 组成。

- 第二行由字符 `"asdfghjkl"` 组成。

- 第三行由字符 `"zxcvbnm"` 组成。

示例 1:

**输入:**words = ["Hello","Alaska","Dad","Peace"]

输出:["Alaska","Dad"]

解释:

由于不区分大小写,"a""A" 都在美式键盘的第二行。

示例 2:

输入:words = ["omk"]

输出:[]

示例 3:

输入:words = ["adsdf","sfd"]

输出:["adsdf","sfd"]

提示:

- `1 <= words.length <= 20`

- `1 <= words[i].length <= 100`

- `words[i]` 由英文字母(小写和大写字母)组成

难度: Easy


题解代码

javascript
/**
 * @param {string[]} words
 * @return {string[]}
 */
const hash = {
  'q': 1,
  'w': 1,
  'e': 1,
  'r': 1,
  't': 1,
  'y': 1,
  'u': 1,
  'i': 1,
  'o': 1,
  'p': 1,
  'a': 2,
  's': 2,
  'd': 2,
  'f': 2,
  'g': 2,
  'h': 2,
  'j': 2,
  'k': 2,
  'l': 2,
  'z': 3,
  'x': 3,
  'c': 3,
  'v': 3,
  'b': 3,
  'n': 3,
  'm': 3
}

var findWords = function(words) {
  // const hash = {}
  // 'qwertyuiop'.split('').forEach(item => {
  //   hash[item] = 1
  // })
  // 'asdfghjkl'.split('').forEach(item => {
  //   hash[item] = 2
  // })
  // 'zxcvbnm'.split('').forEach(item => {
  //   hash[item] = 3
  // })
  
  const res = []
  words.forEach(item => {
    const lower = item.toLowerCase()
    for(let i = 1; i < lower.length; i++) {
      if (hash[lower[i]] !== hash[lower[0]]) return
    }
    res.push(item)
  })
  return res
};

技术文档集合