Number of Valid Words in a Sentence LeetCode solution in Python
1import re234class Solution:5def countValidWords(self, sentence: str) -> int:67# parse and get each word from sentence8words = sentence.split()910# regular expression pattern for valid words11pattern = re.compile(r"^([a-z]+\-?[a-z]+[!\.,]?)$|^([a-z]*[!\.,]?)$")1213# valid word count14count = 01516# scan each word from word pool17for word in words:1819# judge whether current word is valid or not20match = re.match(pattern, word)2122if match:23count += 12425return count