Solution to LeetCode 2047 Number of Valid Words in a Sentence.
LeetCode 2047
Number of Valid Words in a Sentence (Easy). [link]
Split the sentence into tokens by white space. We have to check whether a word is valid. A word is not valid if either of the following condition satisfies: 1) there is any number in the word 2) > 1 ‘-‘ 3) ‘-‘ in the beginning or at the end 4) the left or right letter of ‘-‘ is not lowercase letter 5) punctuation is not at the end.
Time complexity O(N). Space complexity (1).
class Solution(object):
def countValidWords(self, sentence):
"""
:type sentence: str
:rtype: int
"""
def check(s):
valid = False # check the number of -
for i, char in enumerate(s):
# there is numbers OR punctuation not at the end
if char.isdigit() or (char in "!.," and i < len(s) - 1):
return False
if char == '-':
if valid or i == 0 or i == len(s) - 1 or not s[i-1].islower() or not s[i+1].islower():
return False
valid = True
return True
return sum(check(s) for s in sentence.split())