每日一题 2047. 句子中的有效单词数

简介: 每日一题 2047. 句子中的有效单词数

判断句子中的有效单词数。


题目比较简单,将句子拆分成单词,然后判断单词是否有效。


但是“有效”条件有点繁琐:


如果一个 token 同时满足下述条件,则认为这个 token 是一个有效单词:


1.不含数字

2.至多一个 连字符 '-' 。如果存在,连字符两侧应当都存在小写字母("a-b" 是一个有效单词,但 "-ab" 和 "ab-" 不是有效单词)。

3.至多一个 标点符号。如果存在,标点符号应当位于 token 的 末尾 。

官方题解:

class Solution:
    def countValidWords(self, sentence: str) -> int:
        def valid(s):
            hasHyphens = False
            for i, ch in enumerate(s):
                if ch.isdigit() or ch in "!.," and i < len(s)-1:
                    return False
                if ch == '-':
                    if hasHyphens or i==0 or i== len(s)-1 or not s[i-1].islower() or not s[i+1].islower():
                        return False
                    hasHyphens = True
            return True
                
        return sum(valid(s) for s in sentence.split())        

自己写的:

前几遍没过,容易漏条件。

class Solution:
    def countValidWords(self, sentence: str) -> int:
        tokens = sentence.split()
        count = 0
        print(tokens)
        
        for token in tokens:
            istoken = True
            hasHyphens = False
            for i,x in enumerate(token):
                if x.isdigit():
                    istoken = False
                    break 
                if x in "!.," and i != len(token)-1:
                    istoken = False
                    break
                if x == '-':
                    if hasHyphens or i==0 or i== len(token)-1 or not token[i-1].islower() or not token[i+1].islower():
                        istoken = False
                        break
                    hasHyphens = True 
            if istoken and token:
                count += 1
        
        return count

补充:

学到的三个简化代码方法:

一、enumerate(iterable,start=0)返回一个枚举对象,里面包含一个计数值和迭代对象iterable生成的值。

该方法等价于:

def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1

内置函数 — Python 3.10.2 文档


二、sum(iterable, /, start=0) 也可以对[True,True,False]这样布尔类型求和,返回其中True个数。


从 start 开始自左向右对 iterable 的项求和并返回总计值。 iterable 的项通常为数字,而 start 值则不允许为字符串。


三、用 in 代替多个== or == or ==


如: ch in "!.,"


x in [1,3,5],


相关文章
|
1月前
【力扣】1832.判断句子是否为全字母句
【力扣】1832.判断句子是否为全字母句
|
1月前
每日一题(数字颠倒,单词倒排)
每日一题(数字颠倒,单词倒排)
18 1
|
1月前
leetcode-2047:句子中的有效单词数
leetcode-2047:句子中的有效单词数
24 0
|
1月前
leetcode-884:两句话中的不常见单词
leetcode-884:两句话中的不常见单词
18 0
|
1月前
leetcode-1816:截断句子
leetcode-1816:截断句子
26 0
|
C语言
LeetCode刷题集(四)(LeetCode2114.句子中的最多单词数)
LeetCode刷题集(四)(LeetCode2114.句子中的最多单词数)
43 0
2114. 句子中的最多单词数
一个 句子 由一些 单词 以及它们之间的单个空格组成,句子的开头和结尾不会有多余空格。 给你一个字符串数组 sentences ,其中 sentences[i] 表示单个 句子 。 请你返回单个句子里 单词的最多数目 。
72 0
LeetCode 1832. 判断句子是否为全字母句
全字母句 指包含英语字母表中每个字母至少一次的句子。
86 0
每日一题——最常见的单词
每日一题——最常见的单词
52 0