Python 2047.py
class Solution:
def countValidWords(self, sentence: str) -> int:
valid = 0
tokens = sentence.split(" ")
for t in tokens:
if not t: # multiple spaces => empty tokens
continue
# no digits
if re.search("[0-9]", t):
continue
# punctuation only at the end
if t[-1] in [ "!", ".", "," ]:
t = t[:-1]
# could be empty now
if not t:
valid += 1
continue
# no more punctuation
if re.search("[\!\.\,]", t):
continue
# at most one hyphen
if t.count("-") > 1:
continue
if t[0] == "-" or t[-1] == "-":
continue
valid += 1
return valid
Difficulty
and has an acceptance rate of about 31% (100k+ submissions).
Typical patterns to solve this problem:
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a class Solution with a method countValidWords that receives a string sentence and returns the number of tokens that satisfy a specific set of linguistic rules. The algorithm proceeds by splitting the input on spaces, discarding empty fragments that arise from consecutive spaces, and then applying a series of regular-expression checks and character inspections to decide whether each token is valid. The final count is accumulated in the variable valid and returned.
Tokenization and Early Elimination
The first logical block isolates individual words by using the built-in split method with a single space as the delimiter.
tokens = sentence.split(" ")
for t in tokens:
if not t: # multiple spaces => empty tokens
continue
By checking if not t the code immediately skips any empty strings that result from multiple consecutive spaces, ensuring that only non-empty fragments are examined further. This early elimination prevents unnecessary processing of tokens that could never be valid.
Digit Exclusion
The next step removes any token that contains a numeric character. A regular expression searches for any digit, and the token is discarded if a match is found.
if re.search("[0-9]", t):
continue
This guard guarantees that tokens with embedded numbers are never counted as valid, aligning with the rule that a valid word must be free of digits.
Handling Terminal Punctuation
The algorithm permits a single punctuation mark (!, ., or ,) at the very end of a token. If the last character belongs to this set, it is stripped off, and the remaining substring is examined.
if t[-1] in ["!", ".", ","]:
t = t[:-1]
# could be empty now
if not t:
valid += 1
continue
When the removal of the trailing punctuation leaves an empty string, the token is considered valid (for example, a solitary punctuation mark). The count is incremented, and processing moves to the next token.
Prohibiting Internal Punctuation
After any trailing punctuation has been removed, the code ensures that no other punctuation characters appear within the token. A second regular-expression search looks for any of the three punctuation symbols anywhere in the remaining string.
if re.search("[\!\.\,]", t):
continue
If such a character is found, the token is rejected, enforcing the rule that punctuation may appear only at the end.
Hyphen Constraints
Hyphens are allowed under strict conditions: at most one hyphen may appear, and it cannot be the first or last character of the token. The implementation checks the count of hyphens and the positions of any hyphen.
if t.count("-") > 1:
continue
if t[0] == "-" or t[-1] == "-":
continue
These checks guarantee that tokens like well-known pass, while -start, end-, or a-b-c are excluded.
Successful Validation
If a token survives all preceding filters, it is deemed valid, and the accumulator is incremented.
valid += 1
The loop then proceeds to the next token until all fragments have been examined.
Edge Cases Addressed
The code explicitly handles several edge conditions. Empty tokens generated by multiple spaces are ignored, preventing false positives. Tokens consisting solely of a punctuation character are accepted after the trailing-punctuation removal step, as the subsequent emptiness check adds to the count. Tokens that become empty after stripping a trailing punctuation mark are also counted as valid, reflecting the rule that a lone punctuation mark qualifies as a word. Hyphen placement is rigorously checked to avoid acceptance of tokens that start or end with a hyphen, as well as tokens containing more than one hyphen. Digits embedded anywhere in a token trigger immediate rejection, covering cases such as a1b or 123.
Performance Optimizations Observed
The implementation minimizes work by applying cheap checks early in the processing pipeline. The empty-token guard and digit-search are performed before any string slicing, reducing the number of times the more expensive regular-expression engine is invoked. Stripping of trailing punctuation occurs only when the last character matches one of the allowed symbols, avoiding unnecessary string copying for the majority of tokens. The hyphen count check uses the built-in count method, which is implemented in C and runs faster than a manual iteration. By ordering the validation steps from least to most costly, the algorithm reduces overall runtime, especially for long sentences with many tokens that fail early criteria. The use of a single accumulator variable valid avoids the overhead of building auxiliary collections, keeping memory usage low.
ELI5 - Simplified Explanation
Imagine a big sentence made of many small words all stuck together like train cars. This piece of code acts like a very careful guard standing at a gate to check each word one by one.
First, the guard takes the whole sentence and chops it into separate pieces wherever there is a space. This makes it easier to look at each word alone.
The guard then starts a checklist for every word. If a word has numbers like one, two, or three inside it, the guard says it is not allowed and skips it.
Next, the guard checks for punctuation marks like dots or commas. If there is a dot at the end, the guard takes it off to see what is left behind. However, the guard is very strict, so if a dot or a comma is hiding in the middle of a word instead of at the very end, the word is not allowed.
After that, the guard looks to see if there is a tiny hyphen inside the word. Usually, that is fine, but if there are too many hyphens, or if one is hanging off the very front or the very back of the word, the guard stops and moves on to the next one.
Whenever a word passes all of these strict tests, the guard adds a little gold star to a counter to show that this word is perfectly valid.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | Python | ||||||
| leetcode.ca | C++ | Java | Python | Go | TS | ||||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 2114: Maximum Number of Words Found in Sentences
Solved On The Same Day
- problem 859: Buddy Strings
- problem 914: X of a Kind in a Deck of Cards
- problem 925: Long Pressed Name
- problem 1346: Check If N and Its Double Exist
- problem 1805: Number of Different Integers in a String
- problem 1909: Remove One Element to Make the Array Strictly Increasing
- problem 2469: Convert the Temperature
- problem 2525: Categorize Box According to Criteria
- problem 2591: Distribute Money to Maximum Children
- problem 2614: Prime In Diagonal
- problem 2660: Determine the Winner of a Bowling Game
- problem 2760: Longest Even Odd Subarray With Threshold
- problem 2765: Longest Alternating Subarray
- problem 1255: Maximum Score Words Formed by Letters
- problem 2251: Number of Flowers in Full Bloom
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality