2173. Number of Valid Words in a Sentence
My accepted Python solution to LeetCode problem 2173, Number of Valid Words in a Sentence, running in 11ms.
- Difficulty: Easy
- Python
- Runtime 11ms
- Memory 17.7MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 11ms, memory 17.7MB, accepted 2025-12-29.
class Solution:
def countValidWords(self, sentence: str) -> int:
import re
pattern = r'^([a-z]+(-[a-z]+)?)?[!.,]?$'
tokens = sentence.split()
count = 0
for token in tokens:
if token and re.match(pattern, token):
count += 1
return count