leetcode刷题记录--Keyboard Row

题目

难度:easy

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.


keyboard.png

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.

第一次解法

/**
 * @param {string[]} words
 * @return {string[]}
 */
var findWords = function(words) {
    let row1 = new Set('qwertyuiopQWERTYUIOP');
    let row2 = new Set('asdfghjklASDFGHJKL');
    let row3 = new Set('zxcvbnmZXCVBNM');
    
    let isSameRow = function(letters, row) {
        return letters.every(letter => row.has(letter));
    }
    
    return words.filter((word) => {
        let letters = word.split('');
        return isSameRow(letters, row1) || isSameRow(letters, row2) || isSameRow(letters, row3);
    });
};# runtime : 99ms

你可能感兴趣的:(leetcode刷题记录--Keyboard Row)