Maximum Number of Words You Can Type
Problem
Given a string text of space-separated words and a string brokenLetters of distinct lowercase letters, return how many words can be typed.
Input
text = "hello world", brokenLetters = "ad"Output
1"hello" has no broken letters; "world" has "d".
def can_be_typed_words(text, brokenLetters):
bad = set(brokenLetters)
cnt = 0
for w in text.split():
if not any(c in bad for c in w):
cnt += 1
return cnt
function canBeTypedWords(text, brokenLetters) {
const bad = new Set(brokenLetters);
let cnt = 0;
for (const w of text.split(' ')) {
let ok = true;
for (const c of w) if (bad.has(c)) { ok = false; break; }
if (ok) cnt++;
}
return cnt;
}
class Solution {
public int canBeTypedWords(String text, String brokenLetters) {
Set<Character> bad = new HashSet<>();
for (char c : brokenLetters.toCharArray()) bad.add(c);
int cnt = 0;
for (String w : text.split(" ")) {
boolean ok = true;
for (char c : w.toCharArray()) if (bad.contains(c)) { ok = false; break; }
if (ok) cnt++;
}
return cnt;
}
}
int canBeTypedWords(string text, string brokenLetters) {
unordered_set<char> bad(brokenLetters.begin(), brokenLetters.end());
int cnt = 0; stringstream ss(text); string w;
while (ss >> w) {
bool ok = true;
for (char c : w) if (bad.count(c)) { ok = false; break; }
if (ok) cnt++;
}
return cnt;
}
Explanation
A word can be typed only if none of its letters are broken. So we go word by word and check each one against the set of broken keys.
First we put the broken letters into a set called bad. A set gives instant "is this letter broken?" lookups, which keeps the check fast.
Then we split text into words and, for each word, ask: does it contain any character that is in bad? If it contains none, the word is typeable and we add one to cnt.
Example: text = "hello world", brokenLetters = "ad". The word "hello" has no a or d, so it counts. The word "world" contains d, so it does not. The answer is 1.