Number of Valid Words in a Sentence LeetCode solution in C++

1
#include <regex>
2

3
class Solution {
4
public:
5
int countValidWords(string sentence) {
6
int count = 0;
7

8
// Defining the regex pattern
9
regex valid_word("[a-z]*([a-z]-[a-z])?[a-z]*[!,.]?");
10

11
// splitting the sentence to words
12
stringstream s(sentence);
13
string word;
14
while (getline(s, word, ' ')) {
15
// Checking if the word matches the regex pattern
16
if (word != "" && regex_match(word, valid_word)) {
17
++count;
18
}
19
}
20

21
return count;
22
}
23
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0