LeetCode solutions

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

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 11ms, memory 17.7MB, accepted 2025-12-29.

python
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

Source