Leetcode 1935. Maximum Number of Words You Can Type
You are given a string text of words that are separated by one or more spaces, and a string brokenLetters of lowercase English letters that contains some broken letters.
Return the number of words in the text you can fully type using the keyboard provided that the broken letters might not work properly for typing. A word is defined as a sequence of non-space characters.
text = "hello world", brokenLetters = "ad"1text = "leet code", brokenLetters = "lt"1text = "leet code", brokenLetters = "e"0brokenLetters string be empty?
brokenLetters is empty, then all letters are functional, and all words can be typed.text and brokenLetters?
text and brokenLetters can be of length up to 10,000.brokenLetters to enable O(1) average lookup time.text based on spaces to process each word separately.brokenLetters set. If not, it can be typed.Steps:
brokenLetters string into a set for efficient lookup.text by spaces to get individual words.brokenLetters set.brokenLetters.text and W is the number of words.Overall, the time complexity is O(T + B + W * L).
Here’s how we can implement this in C++:
#include <iostream>
#include <unordered_set>
#include <sstream>
using namespace std;
int canBeTypedWords(string text, string brokenLetters) {
unordered_set<char> broken(brokenLetters.begin(), brokenLetters.end());
istringstream iss(text);
string word;
int count = 0;
bool canType = true;
while (iss >> word) {
canType = true;
for (char c : word) {
if (broken.find(c) != broken.end()) {
canType = false;
break;
}
}
if (canType) count++;
}
return count;
}
int main() {
// Example usage:
string text = "hello world";
string brokenLetters = "ad";
cout << canBeTypedWords(text, brokenLetters) << endl; // Output: 1
return 0;
}
This code uses a set to store broken letters for fast lookup and processes each word by checking each character to see if it’s a broken letter. If a word doesn’t contain any broken letters, it is considered typable.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?