Skip to content

Commit 33013ac

Browse files
Create 0501-Keyboard Rows
Keyboard-Rows
1 parent 563e69d commit 33013ac

File tree

1 file changed

+319
-0
lines changed

1 file changed

+319
-0
lines changed
Lines changed: 319 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,319 @@
1+
---
2+
id: Keyboard-Rows
3+
title: Keyboard-Rows
4+
sidebar_label: Keyboard-Rows
5+
tags:
6+
- String
7+
- Array
8+
- LeetCode
9+
---
10+
11+
## Problem Description
12+
13+
| Problem Statement | Solution Link | LeetCode Profile |
14+
| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ |
15+
| [Keyboard-Rows](https://leetcode.com/problems/Keyboard-Rows/description/) | [Keyboard-Rows Solution on LeetCode](https://leetcode.com/problems/Keyboard-Rows/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) |
16+
17+
18+
## Problem Description
19+
20+
Given an array of strings `words`, return the words that can be typed using letters of the alphabet on only one row of the American keyboard.
21+
22+
American keyboard rows:
23+
1. "qwertyuiop"
24+
2. "asdfghjkl"
25+
3. "zxcvbnm"
26+
27+
### Example 1
28+
29+
**Input:** `words = ["Hello","Alaska","Dad","Peace"]`
30+
**Output:** `["Alaska","Dad"]`
31+
32+
### Example 2
33+
34+
**Input:** `words = ["omk"]`
35+
**Output:** `[]`
36+
37+
### Example 3
38+
39+
**Input:** `words = ["adsdf","sfd"]`
40+
**Output:** `["adsdf","sfd"]`
41+
42+
### Constraints
43+
44+
- `1 <= words.length <= 20`
45+
- `1 <= words[i].length <= 100`
46+
- `words[i]` consists of English letters (both lowercase and uppercase).
47+
48+
## Approach
49+
50+
We can solve this problem efficiently by checking each word to see if all its characters belong to the same row on the keyboard. We can utilize sets for the characters of each row for quick lookup.
51+
52+
## Solution in Python
53+
54+
```python
55+
def findWords(words):
56+
row1 = set("qwertyuiop")
57+
row2 = set("asdfghjkl")
58+
row3 = set("zxcvbnm")
59+
60+
def check_word(word):
61+
if word[0].lower() in row1:
62+
row = row1
63+
elif word[0].lower() in row2:
64+
row = row2
65+
else:
66+
row = row3
67+
68+
for char in word:
69+
if char.lower() not in row:
70+
return False
71+
return True
72+
73+
result = []
74+
for word in words:
75+
if check_word(word):
76+
result.append(word)
77+
78+
return result
79+
80+
# Example usage:
81+
words = ["Hello","Alaska","Dad","Peace"]
82+
print(findWords(words)) # Output: ["Alaska","Dad"]
83+
```
84+
85+
## Solution in Java
86+
87+
```java
88+
import java.util.ArrayList;
89+
import java.util.HashSet;
90+
import java.util.List;
91+
import java.util.Set;
92+
93+
public class Solution {
94+
public String[] findWords(String[] words) {
95+
Set<Character> row1 = new HashSet<>();
96+
Set<Character> row2 = new HashSet<>();
97+
Set<Character> row3 = new HashSet<>();
98+
99+
for (char c : "qwertyuiop".toCharArray()) row1.add(c);
100+
for (char c : "asdfghjkl".toCharArray()) row2.add(c);
101+
for (char c : "zxcvbnm".toCharArray()) row3.add(c);
102+
103+
List<String> result = new ArrayList<>();
104+
105+
for (String word : words) {
106+
if (isSingleRow(word, row1, row2, row3)) {
107+
result.add(word);
108+
}
109+
}
110+
111+
return result.toArray(new String[0]);
112+
}
113+
114+
private boolean isSingleRow(String word, Set<Character> row1, Set<Character> row2, Set<Character> row3) {
115+
Set<Character> currentRow = determineRow(word.charAt(0), row1, row2, row3);
116+
117+
for (int i = 1; i < word.length(); i++) {
118+
if (!currentRow.contains(Character.toLowerCase(word.charAt(i)))) {
119+
return false;
120+
}
121+
}
122+
123+
return true;
124+
}
125+
126+
private Set<Character> determineRow(char c, Set<Character> row1, Set<Character> row2, Set<Character> row3) {
127+
char lowerC = Character.toLowerCase(c);
128+
129+
if (row1.contains(lowerC)) {
130+
return row1;
131+
} else if (row2.contains(lowerC)) {
132+
return row2;
133+
} else {
134+
return row3;
135+
}
136+
}
137+
138+
public static void main(String[] args) {
139+
Solution sol = new Solution();
140+
String[] words = {"Hello","Alaska","Dad","Peace"};
141+
String[] result = sol.findWords(words);
142+
for (String word : result) {
143+
System.out.println(word);
144+
}
145+
}
146+
}
147+
```
148+
149+
## Solution in C++
150+
151+
```cpp
152+
#include <iostream>
153+
#include <vector>
154+
#include <unordered_set>
155+
156+
using namespace std;
157+
158+
class Solution {
159+
public:
160+
vector<string> findWords(vector<string>& words) {
161+
unordered_set<char> row1 {'q','w','e','r','t','y','u','i','o','p'};
162+
unordered_set<char> row2 {'a','s','d','f','g','h','j','k','l'};
163+
unordered_set<char> row3 {'z','x','c','v','b','n','m'};
164+
165+
vector<string> result;
166+
167+
for (const string& word : words) {
168+
if (isSingleRow(word, row1, row2, row3)) {
169+
result.push_back(word);
170+
}
171+
}
172+
173+
return result;
174+
}
175+
176+
bool isSingleRow(const string& word, unordered_set<char>& row1, unordered_set<char>& row2, unordered_set<char>& row3) {
177+
unordered_set<char>* currentRow = determineRow(word[0], row1, row2, row3);
178+
179+
for (int i = 1; i < word.size(); i++) {
180+
if (currentRow->find(tolower(word[i])) == currentRow->end()) {
181+
return false;
182+
}
183+
}
184+
185+
return true;
186+
}
187+
188+
unordered_set<char>* determineRow(char c, unordered_set<char>& row1, unordered_set<char>& row2, unordered_set<char>& row3) {
189+
char lowerC = tolower(c);
190+
191+
if (row1.find(lowerC) != row1.end()) {
192+
return &row1;
193+
} else if (row2.find(lowerC) != row2.end()) {
194+
return &row2;
195+
} else {
196+
return &row3;
197+
}
198+
}
199+
};
200+
201+
int main() {
202+
Solution sol;
203+
vector<string> words = {"Hello","Alaska","Dad","Peace"};
204+
vector<string> result = sol.findWords(words);
205+
for (const string& word : result) {
206+
cout << word << endl;
207+
}
208+
return 0;
209+
}
210+
```
211+
212+
## Solution in C
213+
214+
```c
215+
#include <stdio.h>
216+
#include <stdbool.h>
217+
#include <ctype.h>
218+
#include <string.h>
219+
220+
bool isSingleRow(char* word, char* row1, char* row2, char* row3) {
221+
char* currentRow;
222+
if (strchr(row1, tolower(word[0]))) {
223+
currentRow = row1;
224+
} else if (strchr(row2, tolower(word[0]))) {
225+
currentRow = row2;
226+
} else {
227+
currentRow = row3;
228+
}
229+
230+
for (int i = 1; i < strlen(word); i++) {
231+
if (!strchr(currentRow, tolower(word[i]))) {
232+
return false;
233+
}
234+
}
235+
236+
return true;
237+
}
238+
239+
void findWords(char** words, int wordsSize, char** result, int* returnSize) {
240+
char* row1 = "qwertyuiop";
241+
char* row2 = "asdfghjkl";
242+
char* row3 = "zxcvbnm";
243+
244+
*returnSize = 0;
245+
for (int i = 0; i < wordsSize; i++) {
246+
if (isSingleRow(words[i], row1, row2, row3)) {
247+
result[*returnSize] = words[i];
248+
(*returnSize)++;
249+
}
250+
}
251+
}
252+
253+
int main() {
254+
char* words[] = {"Hello","Alaska","Dad","Peace"};
255+
int wordsSize = 4;
256+
char* result[wordsSize];
257+
int returnSize;
258+
259+
findWords(words, wordsSize, result, &returnSize);
260+
261+
for (int i = 0; i < returnSize; i++) {
262+
printf("%s\n", result[i]);
263+
}
264+
265+
return 0;
266+
}
267+
```
268+
269+
## Solution in JavaScript
270+
271+
```javascript
272+
/**
273+
* @param {string[]} words
274+
* @return {string[]}
275+
*/
276+
var findWords = function(words) {
277+
const row1 = new Set("qwertyuiop");
278+
const row2 = new Set("asdfghjkl");
279+
const row3 = new Set("zxcvbnm");
280+
281+
const isSingleRow = (word) => {
282+
let firstChar = word[0].toLowerCase();
283+
if (row1.has(firstChar)) {
284+
row = row1;
285+
} else if (row2.has(firstChar)) {
286+
row = row2;
287+
} else {
288+
row = row3;
289+
}
290+
291+
for (let i = 1; i < word.length; i++) {
292+
if (!row.has(word[i].toLowerCase())) {
293+
return false;
294+
}
295+
}
296+
return true;
297+
}
298+
299+
let result = [];
300+
for (let word of words) {
301+
if (isSingleRow(word)) {
302+
result.push(word);
303+
}
304+
}
305+
306+
return result;
307+
};
308+
309+
// Example usage:
310+
let words = ["Hello","Alaska","Dad","Peace"];
311+
console.log(findWords(words)); // Output: ["Alaska","Dad"]
312+
```
313+
314+
## Step-by-Step Algorithm
315+
316+
1. **Input Parsing**: Read the input array of words.
317+
2. **Keyboard Rows Initialization**: Define three sets representing characters in each row of the keyboard.
318+
3. **Function Definition**: Implement a function to determine if a word can be typed using characters from a single keyboard row.
319+
4. **Iteration and Filtering**: Iterate through each word in the input array and

0 commit comments

Comments
 (0)