Skip to content

Practice Number of Valid Words in a Sentence

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Easy#2047
LeetCode Problem

Number of Valid Words in a Sentence

Problem Statement

Split sentence into nonempty tokens at spaces. A valid token contains only lowercase letters, an optional hyphen, and an optional punctuation mark from !, ., or ,. It contains no digits. There may be at most one hyphen, and it must have a lowercase letter immediately on both sides. There may be at most one punctuation mark, and it must be the final character. A punctuation-only token such as ! is valid. Return the number of valid tokens.

Source: Number of Valid Words in a Sentence on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
sentence = "cat and  dog"
Output
3

# Example 2

Input
sentence = "!this  1-s b8d!"
Output
0

# Example 3

Input
sentence = "alice and  bob are playing stone-game10"
Output
5

Constraints

1 <= sentence.length <= 1000
sentence only contains lowercase English letters, digits, ' ', '-', '!', '.', and ','.
There will be at least 1 token.

Related LeetCode Problems

Practice more problems similar to Number of Valid Words in a Sentence.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.