You are given a string sentence
that consists of words separated by spaces. Each word contains only lowercase letters, hyphens, and/or punctuation symbols (!
, .
and ,
). A valid word follows these rules:
Implement a function that counts the number of valid words in the given sentence.
class Solution:
def countValidWords(self, sentence: str) -> int:
def is_valid(word):
word_len = len(word)
if word_len == 0:
return False
has_hyphen = False
for i, char in enumerate(word):
if char.isdigit():
return False
if char in '.,!':
if i != word_len - 1:
return False
if char == '-':
if has_hyphen or i == 0 or i == word_len - 1:
return False
if not (word[i - 1].isalpha() and word[i + 1].isalpha()):
return False
has_hyphen = True
return True
words = sentence.split()
valid_word_count = 0
for word in words:
if is_valid(word):
valid_word_count += 1
return valid_word_count
# Example usage:
# sol = Solution()
# print(sol.countValidWords("cat and dog")) # Output: 3
# print(sol.countValidWords("!this 1-s b8d!")) # Output: 0
In this implementation, the is_valid
function is responsible for verifying if a word meets the specified criteria. The main countValidWords
function iterates through the sentence, splits it into words, and counts the valid words using the helper function.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?