1935. Maximum Number of Words You Can Type #2176
-
Topics: There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly. Given a string Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine how many words in a given string can be fully typed using a keyboard where some keys are broken. The solution involves checking each word in the input string to see if it contains any of the broken letters. If a word does not contain any broken letters, it can be typed completely. Approach
Let's implement this solution in PHP: 1935. Maximum Number of Words You Can Type <?php
/**
* @param String $text
* @param String $brokenLetters
* @return Integer
*/
function canBeTypedWords($text, $brokenLetters) {
$words = explode(' ', $text);
$brokenSet = str_split($brokenLetters);
$count = 0;
foreach ($words as $word) {
$canType = true;
foreach (str_split($word) as $char) {
if (in_array($char, $brokenSet)) {
$canType = false;
break;
}
}
if ($canType) {
$count++;
}
}
return $count;
}
// Test cases
echo canBeTypedWords("hello world", "ad") . "\n"; // Output: 1
echo canBeTypedWords("leet code", "lt") . "\n"; // Output: 1
echo canBeTypedWords("leet code", "e") . "\n"; // Output: 0
?> Explanation:
This approach efficiently checks each word for broken characters using a set for quick lookups, ensuring optimal performance even for the upper constraint limits. The solution is straightforward and leverages basic string and array operations to achieve the desired result. |
Beta Was this translation helpful? Give feedback.
We need to determine how many words in a given string can be fully typed using a keyboard where some keys are broken. The solution involves checking each word in the input string to see if it contains any of the broken letters. If a word does not contain any broken letters, it can be typed completely.
Approach
text
consists of words separated by single spaces. We split this string into individual words.brokenLetters
into a set (or an array) for efficient lookup. This allows us to quickly check if a letter is broken.