First, we can create a hashmap of all the broken letters on our keyboard:
vector<int> broken(26, 0);
for (char& c : brokenLetters) {
++broken[c-'a'];
}
Then, we iterate through text, keeping track of the number of words we can fully type out using ans.
To verify if we can type out a word, we will keep track of a valid boolean value.
Now, when we iterate through text, if we find a letter that we cannot type, we can simply set valid to false.
Afterwards, when we face a single space, if valid is true then we can increment ans, else we do nothing.
Regardless, we will set valid back to true and continue iterating through the next word.
int ans = 0;
bool valid = true;
for (char& c : text) {
if (c == ' ') {
if (valid) {
++ans;
}
valid = true;
} else if (broken[c-'a'] == 1) {
valid = false;
}
}
if (valid) {
++ans;
}
return ans;
code
class Solution {
public:
int canBeTypedWords(string text, string brokenLetters) {
vector<int> broken(26, 0);
for (char& c : brokenLetters) {
++broken[c-'a'];
}
int ans = 0;
bool valid = true;
for (char& c : text) {
if (c == ' ') {
if (valid) {
++ans;
}
valid = true;
} else if (broken[c-'a'] == 1) {
valid = false;
}
}
if (valid) {
++ans;
}
return ans;
}
};
complexity
- Time:
O(n)wherenis the number of character insidetext- Space:
O(1)
time taken
- 0 minutes and 0 seconds (i forgot to time)