Number of Valid Words in a Sentence LeetCode solution in C++
1#include <regex>23class Solution {4public:5int countValidWords(string sentence) {6int count = 0;78// Defining the regex pattern9regex valid_word("[a-z]*([a-z]-[a-z])?[a-z]*[!,.]?");1011// splitting the sentence to words12stringstream s(sentence);13string word;14while (getline(s, word, ' ')) {15// Checking if the word matches the regex pattern16if (word != "" && regex_match(word, valid_word)) {17++count;18}19}2021return count;22}23};