#2047

Number of Valid Words in a Sentence

Easy
LeetCode ↗

Approaches

💡

Intuition

Time UnknownSpace Unknown

We can start by splitting the sentence into tokens based on spaces and then check each token for validity. This approach is straightforward but inefficient as it checks each token individually.

⚙️

Algorithm

3 steps
  1. 1Step 1: Split the sentence into tokens using spaces as delimiters.
  2. 2Step 2: For each token, check if it meets the validity criteria: contains only valid characters, has at most one hyphen surrounded by letters, and has at most one punctuation mark at the end.
  3. 3Step 3: Count the number of valid tokens and return the count.
solution.py31 lines
1# Full working Python code
2
3def countValidWords(sentence):
4    tokens = sentence.split()
5    valid_count = 0
6    for token in tokens:
7        if isValid(token):
8            valid_count += 1
9    return valid_count
10
11
12def isValid(token):
13    if not token:
14        return False
15    hyphen_count = token.count('-')
16    if hyphen_count > 1:
17        return False
18    if hyphen_count == 1:
19        hyphen_index = token.index('-')
20        if hyphen_index == 0 or hyphen_index == len(token) - 1:
21            return False
22        if not (token[hyphen_index - 1].islower() and token[hyphen_index + 1].islower()):
23            return False
24    punctuation_count = sum(1 for char in token if char in '!.')
25    if punctuation_count > 1:
26        return False
27    if punctuation_count == 1:
28        if token[-1] not in '!.':
29            return False
30        token = token[:-1]  # Remove punctuation for further checks
31    return all(c.islower() or c == '-' for c in token)

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.