500.耳机行(javascript)500.KeyboardRow

原创
小哥 3年前 (2022-11-10) 阅读数 3 #大杂烩

给你一个字符串数组 words ,中只能使用return。 美式键盘 用同一行字母印刷的单词。键盘如下图所示。

美式键盘 中:

第一行由角色制作 “qwertyuiop” 组成。
第二行由字符组成 “asdfghjkl” 组成。
第三行由字符组成 “zxcvbnm” 组成。
Given an array of strings words, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below.

In the American keyboard:

  • the first row consists of the characters “qwertyuiop”,
  • the second row consists of the characters “asdfghjkl”, and
  • the third row consists of the characters “zxcvbnm”.

示例 1:

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

示例 2:

输入:words = ["omk"]
输出:[]

示例 3:

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

提示:

  • 1 <= words.length <= 20
  • 1 <= words[i].length <= 100
  • words[i] 由英文字母(小写和大写)组成

分析主题:

var findWords = function (words) {
    let one = qwertyuiop,
        two = asdfghjkl,
        three = zxcvbnm,
        newList = [];
        // 因为比较了所有小写字母,所以数组字符串被转换为小写字母。
    let words1 = words.map((item) => item.toLowerCase())
    //进行遍历
    for (let i = 0; i < words1.length; i++) {
        let item = words1[i]
        //根据每个字符串的第一项,确定用于后续判断的字符行。
        let standard = one.includes(item[0]) ? one : two.includes(item[0]) ? two : three 
        let isShow = true //作为标志,当存在不一致的字符时,返回。false
        for (let j = 0; j < item.length; j++) {
            if (!standard.includes(item[j])) {
                isShow = false
                break
            }
        }
        //isShow根据,这里使用了徽标。isShow为了判断是否符合,将添加合规性,将短路合规性。
        //值得注意的是 words1里面有所有的小写字符串。追加时,使用原始数组中的字符串。
        isShow && newList.push(words[i])
    }
    return newList
};

var findWords = function (words) {
    let one = qwertyuiop,
        two = asdfghjkl,
        three = zxcvbnm,
        newList = [];
    let words1 = words.map((item) => item.toLowerCase())
    for (let i = 0; i < words1.length; i++) {
        let item = words1[i]
        let standard = one.includes(item[0]) ? one : two.includes(item[0]) ? two : three 
        let isShow = true
        for (let j = 0; j < item.length; j++) {
            if (!standard.includes(item[j])) {
                isShow = false
                break
            }
        }
        isShow && newList.push(words[i])
    }
    return newList
};

leetcode: https://leetcode.cn/problems/keyboard-row/

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除