Number of Valid Words in a Sentence LeetCode solution in Python

1
import re
2

3

4
class Solution:
5
def countValidWords(self, sentence: str) -> int:
6

7
# parse and get each word from sentence
8
words = sentence.split()
9

10
# regular expression pattern for valid words
11
pattern = re.compile(r"^([a-z]+\-?[a-z]+[!\.,]?)$|^([a-z]*[!\.,]?)$")
12

13
# valid word count
14
count = 0
15

16
# scan each word from word pool
17
for word in words:
18

19
# judge whether current word is valid or not
20
match = re.match(pattern, word)
21

22
if match:
23
count += 1
24

25
return count

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0