Maximum Number of Words You Can Type

We are given a string text representing words and a string brokenLetters representing the keys that are broken. We need to find the number of words in text that can be typed using this keyboard.

Here’s the code to solve this problem:

  1. Split the text into words.
  2. Check if each word contains any of the broken letters.
  3. Increment the count if the word does not contain any broken letters.
  4. Return the count.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
    def canBeTypedWords(self, text: str, brokenLetters: str) -> int:
        # Convert the broken letters into a set for efficient lookup
        broken_set = set(brokenLetters)

        # Split the text into words
        words = text.split()

        # Initialize a counter for words that can be typed
        count = 0

        # Iterate through each word and check if it can be typed
        for word in words:
            # If the word does not contain any broken letters, increment the count
            if all(letter not in broken_set for letter in word):
                count += 1

        return count

Explanation:

  • We start by converting brokenLetters into a set to make the lookup operation efficient.
  • We split text into words using the split method.
  • We then iterate through each word and use the all function combined with a generator expression to check if the word does not contain any of the broken letters.
  • If the word passes the check, we increment the counter.
  • Finally, we return the counter as the result.