-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKeyboardRow.php
More file actions
65 lines (63 loc) · 1.74 KB
/
Copy pathKeyboardRow.php
File metadata and controls
65 lines (63 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
namespace App;
/**
* Keyboard Row
*
* 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"
*
* Example 1:
* Input: words = ["Hello","Alaska","Dad","Peace"]
* Output: ["Alaska","Dad"]
*
* Example 2:
* Input: words = ["omk"]
* Output: []
*
* Example 3:
* Input: words = ["adsdf","sfd"]
* Output: ["adsdf","sfd"]
*
* https://leetcode.com/problems/keyboard-row
*/
class KeyboardRow
{
/**
* @param array<array-key, string> $words
* @return array<array-key, string>
*/
public function findWords(array $words): array
{
/** @var array<array-key, string> $rows */
$rows = [
'qwertyuiop',
'asdfghjkl',
'zxcvbnm'
];
$result = [];
foreach ($words as $word) {
foreach ($rows as $row) {
$typedLetters = 0;
for ($i = 0, $iMax = strlen($word); $i < $iMax; $i++) {
for ($j = 0, $jMax = strlen($row); $j < $jMax; $j++) {
if (strtolower($word[$i]) === $row[$j]) {
$typedLetters++;
break;
}
}
if ($typedLetters === 0) {
break;
}
}
if (strlen($word) === $typedLetters) {
$result[] = $word;
}
}
}
return $result;
}
}