Skip to content

1935. Maximum Number of Words You Can Type 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  int canBeTypedWords(string text, string brokenLetters) {
    int ans = 0;
    istringstream iss(text);
    vector<bool> broken(26);

    for (const char c : brokenLetters)
      broken[c - 'a'] = true;

    for (string word; iss >> word;)
      ans += canBeTyped(word, broken);

    return ans;
  }

 private:
  bool canBeTyped(const string& word, const vector<bool>& broken) {
    for (const char c : word)
      if (broken[c - 'a'])
        return false;
    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
  public int canBeTypedWords(String text, String brokenLetters) {
    int ans = 0;
    boolean[] broken = new boolean[26];

    for (final char c : brokenLetters.toCharArray())
      broken[c - 'a'] = true;

    for (final String word : text.split(" "))
      ans += canBeTyped(word, broken);

    return ans;
  }

  private int canBeTyped(final String word, boolean[] broken) {
    for (final char c : word.toCharArray())
      if (broken[c - 'a'])
        return 0;
    return 1;
  }
}
1
2
3
4
5
6
7
8
9
class Solution:
  def canBeTypedWords(self, text: str, brokenLetters: str) -> int:
    ans = 0
    broken = set(brokenLetters)

    for word in text.split():
      ans += all(c not in broken for c in word)

    return ans