Number of Valid Words in a Sentence - Problem
A sentence consists of lowercase letters ('a' to 'z'), digits ('0' to '9'), hyphens ('-'), punctuation marks ('!', '.', and ','), and spaces (' ') only. Each sentence can be broken down into one or more tokens separated by one or more spaces ' '.
A token is a valid word if all three of the following are true:
- It only contains lowercase letters, hyphens, and/or punctuation (no digits).
- There is at most one hyphen '-'. If present, it must be surrounded by lowercase characters ("a-b" is valid, but "-ab" and "ab-" are not valid).
- There is at most one punctuation mark. If present, it must be at the end of the token ("ab,", "cd!", and "." are valid, but "a!b" and "c.," are not valid).
Examples of valid words include "a-b.", "afad", "ba-c", "a!", and "!".
Given a string sentence, return the number of valid words in sentence.
Input & Output
Example 1 — Basic Validation
$
Input:
sentence = "cat and dog"
›
Output:
3
💡 Note:
All three words are valid: "cat" (only lowercase), "and" (only lowercase), "dog" (only lowercase). Multiple spaces between words don't affect token validation.
Example 2 — Invalid Words with Digits
$
Input:
sentence = "!this 1-s b8d!"
›
Output:
0
💡 Note:
"!this" is invalid (punctuation must be at end, not start), "1-s" is invalid (contains digit), "b8d!" is invalid (contains digit). No valid words.
Example 3 — Hyphen and Punctuation Rules
$
Input:
sentence = "alice and bob are playing stone-game10"
›
Output:
5
💡 Note:
"alice", "and", "bob", "are", "playing" are all valid. "stone-game10" is invalid due to digits. Hyphen in "stone-game10" would be valid if no digits were present.
Constraints
- 1 ≤ sentence.length ≤ 1000
- sentence only contains lowercase English letters, digits, spaces, hyphens, and punctuation marks
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code