Leetcode 2047. Number of Valid Words in a Sentence
You are given a string sentence
that consists of lowercase letters, digits, hyphens, punctuation marks ('!', '.', ','
), and spaces. You need to count the number of valid words in the sentence.
A valid word is defined as:
'!', '.', ','
), which must be at the end.You need to return the number of valid words in the given sentence
.
sentence
into individual words using space as a delimiter.#include <iostream>
#include <sstream>
#include <cctype>
bool isValidWord(const std::string& word) {
int hyphenCount = 0;
int punctuationCount = 0;
int n = word.size();
for (int i = 0; i < n; ++i) {
char ch = word[i];
if (std::isdigit(ch)) {
return false; // Invalid if contains digits
}
if (ch == '-') {
++hyphenCount;
if (hyphenCount > 1 || i == 0 || i == n - 1 || !std::islower(word[i - 1]) || !std::islower(word[i + 1])) {
return false; // Invalid if more than one hyphen or not surrounded by lowercase letters
}
}
if (ch == '!' || ch == '.' || ch == ',') {
++punctuationCount;
if (punctuationCount > 1 || i != n - 1) {
return false; // Invalid if more than one punctuation mark or not at the end
}
}
if (ch != '-' && ch != '!' && ch != '.' && ch != ',' && !std::islower(ch)) {
return false; // Invalid if contains unexpected characters
}
}
return true;
}
int countValidWords(const std::string& sentence) {
std::istringstream ss(sentence);
std::string word;
int validWordCount = 0;
while (ss >> word) {
if (isValidWord(word)) {
++validWordCount;
}
}
return validWordCount;
}
int main() {
std::string sentence = "cat and dog";
std::cout << "Number of valid words: " << countValidWords(sentence) << std::endl;
return 0;
}
The time complexity is O(n), where n
is the length of the sentence
. This is because each word is processed a constant number of times regardless of its length. The space complexity is also O(n) due to the storage of the words split from the sentence.
This approach ensures that each character in the sentence is checked exactly once within the context of its word, providing an efficient solution to the problem.
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?