Number of Valid Words in a Sentence - Problem
Imagine you're building a smart text processor that needs to validate words in sentences! ๐
You're given a sentence containing lowercase letters, digits, hyphens, punctuation marks (!, ., ,), and spaces. Your task is to count how many valid words exist in this sentence.
A word is considered valid if it follows these strict rules:
- Character Rule: Only lowercase letters, hyphens, and punctuation allowed (no digits!)
- Hyphen Rule: At most one hyphen, and it must be surrounded by lowercase letters (
"a-b"โ ,"-ab"โ,"ab-"โ) - Punctuation Rule: At most one punctuation mark, and it must be at the very end (
"hello!"โ ,"he!llo"โ)
Examples of valid words: "a-b.", "hello", "world!", "x-y", "!"
Goal: Return the total count of valid words in the sentence.
Input & Output
example_1.py โ Basic Mixed Sentence
$
Input:
sentence = "cat and dog"
โบ
Output:
3
๐ก Note:
All three tokens 'cat', 'and', and 'dog' are valid words (only lowercase letters, no digits, no hyphens, no punctuation)
example_2.py โ Complex Validation
$
Input:
sentence = "!this 1-s b8d!"
โบ
Output:
2
๐ก Note:
'!this' is valid (punctuation only at end), '1-s' is invalid (contains digit), 'b8d!' is invalid (contains digit)
example_3.py โ Hyphen Edge Cases
$
Input:
sentence = "alice and bob are playing stone-game10"
โบ
Output:
5
๐ก Note:
'alice', 'and', 'bob', 'are', 'playing' are valid. 'stone-game10' is invalid due to digit '1' and '0'
Constraints
- 1 โค sentence.length โค 1000
- sentence consists of lowercase letters, digits, hyphens, punctuation marks, and spaces only
- There are no leading or trailing spaces in sentence
- Each token is separated by at least one space
Visualization
Tap to expand
Understanding the Visualization
1
Token Splitting
Sentence 'cat and-dog!' gets split into ['cat', 'and-dog!']
2
Rule Inspection
Each token flows through validation: digits check, hyphen rules, punctuation rules
3
Quality Control
Invalid tokens (with digits, bad hyphens, misplaced punctuation) get rejected
4
Valid Count
Only tokens passing all quality checks contribute to the final count
Key Takeaway
๐ฏ Key Insight: Single-pass validation is like having an expert inspector who can check multiple quality standards simultaneously, making the process both faster and more efficient than multiple separate inspections.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code