求助:编写QWERTY单键盘行可输入单词筛选函数(附代码进度)
Got it, let's work through this problem together. You mentioned you started defining the top keyboard keys, so let's build out the rest of the solution step by step.
Step 1: Define the Keyboard Rows
First, we need to map out the three rows of a standard QWERTY keyboard. Using Set objects here is ideal because checking if a character exists in a Set is faster (O(1) time) than using an array's includes() method.
const topRow = new Set('qwertyuiop'); const middleRow = new Set('asdfghjkl'); const bottomRow = new Set('zxcvbnm');
Step 2: Create a Helper Function to Check a Single Word
We'll write a small helper function that takes a word and checks if all its characters belong to the same keyboard row. We'll convert the word to lowercase first to handle case-insensitive inputs (like if a word has uppercase letters).
function isSingleRowWord(word) { const lowerWord = word.toLowerCase(); // Determine which row the first character is in let targetRow; if (topRow.has(lowerWord[0])) { targetRow = topRow; } else if (middleRow.has(lowerWord[0])) { targetRow = middleRow; } else { targetRow = bottomRow; } // Check every character in the word against the target row for (const char of lowerWord) { if (!targetRow.has(char)) { return false; } } return true; }
Step 3: Build the Main Function
Now, the main function will take the input array of words, filter out any words that don't pass our helper function's check, and return the valid ones.
function keyboardWords(words) { const topRow = new Set('qwertyuiop'); const middleRow = new Set('asdfghjkl'); const bottomRow = new Set('zxcvbnm'); function isSingleRowWord(word) { const lowerWord = word.toLowerCase(); let targetRow; if (topRow.has(lowerWord[0])) { targetRow = topRow; } else if (middleRow.has(lowerWord[0])) { targetRow = middleRow; } else { targetRow = bottomRow; } for (const char of lowerWord) { if (!targetRow.has(char)) { return false; } } return true; } // Filter the input array to keep only valid words return words.filter(isSingleRowWord); }
Test It With Your Example
Let's run your sample input to verify:
const words = ['sup', 'dad', 'tree', 'snake', 'pet']; console.log(keyboardWords(words)); // Output: ['dad', 'tree', 'pet']
This matches exactly what you expected!
Optional Optimization
If you want to make the code a bit more concise, you can combine the row checks into a single array of Sets, then check if all characters in the word are contained in one of them:
function keyboardWords(words) { const rows = [ new Set('qwertyuiop'), new Set('asdfghjkl'), new Set('zxcvbnm') ]; return words.filter(word => { const lowerWord = word.toLowerCase(); return rows.some(row => { return [...lowerWord].every(char => row.has(char)); }); }); }
This version does the same thing but uses array methods (some and every) to simplify the logic.
内容的提问来源于stack exchange,提问作者Yaqub

