C o u n t V a l i d W o r d s Count\ Valid\ Words Count Valid Words
https://leetcode-cn.com/problems/number-of-valid-words-in-a-sentence/
题目描述
句子仅由小写字母(‘a’ 到 ‘z’)、数字(‘0’ 到 ‘9’)、连字符(’-’)、标点符号(’!’、’.’ 和 ‘,’)以及空格(’ ')组成。每个句子可以根据空格分解成 一个或者多个 token ,这些 token 之间由一个或者多个空格 ’ ’ 分隔。
如果一个 token 同时满足下述条件,则认为这个 token 是一个有效单词:
仅由小写字母、连字符和/或标点(不含数字)。
至多一个 连字符 ‘-’ 。如果存在,连字符两侧应当都存在小写字母(“a-b” 是一个有效单词,但 “-ab” 和 “ab-” 不是有效单词)。
至多一个 标点符号。如果存在,标点符号应当位于 token 的 末尾 。
这里给出几个有效单词的例子:“a-b.”、“afad”、“ba-c”、“a!” 和 “!” 。
给你一个字符串 sentence ,请你找出并返回 sentence 中 ==有效单词的数目 ==。
题目分析
要点
1. sentence按空格分割成单词。注意,空格可能不止一个。
2. 判断有效单词的条件:
a. 不含数字
b. 最多含有一个’-‘或’!‘或’.‘或’,’
c. ‘-’两侧存在小写字母
d. '!‘或’.‘或’,'必须在末尾
特殊用例
’-!’、’-.’、’-,'不成立
’a-’、’-a’不成立
注意’.‘成立和‘’-.'不成立的情况
方法一:直接if条件逻辑判断
Python3
import re
class Solution:
def countValidWords(self, sentence: str) -> int:
words_list = sentence.split() # 按空格分割
count = 0
for word in words_list:
# 1. 不含数字
if bool(re.search(r'\d', word)):
continue
elif word.count('!') + word.count('.') + word.count(',') > 1:
continue
# 2. 标点符号只能有一个
elif word.count('!') + word.count('.') + word.count(',') == 1:
# 3. 标点符号只能在末尾
if word[-1] == '!' or word[-1] == '.' or word[-1] == ',':
# 注意'.'成立和‘'-.'不成立的情况
if len(word) > 1:
if word[-2] == '-':
continue
# 4. '-'仅有一个,且'-'位置不在前或后
if (word.count('-')) < 1 or (word.count('-') == 1 and word[0] != '-' and word[-1] != '-'):
count += 1
else:
continue
# 4. '-'仅有一个,且'-'位置不在前或后
elif word.count('-') == 1:
if word[0] != '-' and word[-1] != '-':
count += 1
else:
continue
elif word.count('-') > 1:
continue
# 5. 纯字母情况,成立
else:
count += 1
return count
复杂度分析
- 时间复杂度: O ( n ) O(n) O(n),其中 n n n单词数量
- 空间复杂度:
O
(
1
)
O(1)
O(1)
写法二:双循环
复杂度分析
- 时间复杂度: O ( n ) O(n) O(n),其中 n n n单词数量
- 空间复杂度:
O
(
1
)
O(1)
O(1)
class Solution:
def countValidWords(self, sentence: str) -> int:
def helper(word):
n, appear = len(word), False
for i, c in enumerate(word):
if 'a' <= c <= 'z':
continue
elif c == '-':
'''
1、appear:鉴定'-'只有1个
2、not i:不存在元素
3、i == n - 1:'-'在末尾
4、'a' <= word[i-1] <= 'z' and 'a' <= word[i+1] <= 'z':'-'的前一个字符和后一个字符是字母
'''
if appear or not i or i == n - 1 or not ('a' <= word[i-1] <= 'z' and 'a' <= word[i+1] <= 'z'):
return False
appear = True
elif c in '!.,':
if i != n - 1:
return False
else:
return False
return True
return sum(helper(w) for w in sentence.split(' ') if w)
复杂度分析
- 时间复杂度: O ( n 2 ) O(n^2) O(n2),其中 n n n单词数量
- 空间复杂度:
O
(
1
)
O(1)
O(1)
OS:该代码源于leetcode题解Benhao
方法二:正则匹配
Python3
import re
class Solution:
def countValidWords(self, sentence: str) -> int:
return sum(bool(re.match(r'[a-z]*([a-z]-[a-z]+)?[!.,]?$', word)) for word in sentence.split(" ") if word)
复杂度分析
- 时间复杂度: O ( n ) O(n) O(n),其中 n n n单词数量
- 空间复杂度:
O
(
1
)
O(1)
O(1)