2114. 句子中的最多单词数 - 力扣(LeetCode)
为了找出一个句子中单词的最多数目,我们可以采取以下步骤:
-
对于每个句子,首先用空格将其拆分成单词。
-
计算每个句子中单词的数量。
-
返回句子中单词数最多的那个句子的单词数。
在代码实现中,我们可以使用 Python 的 split()
方法来根据空格分割句子。然后,通过遍历所有句子并计算其单词数量,找出最大值。
下面是 Python 代码实现:
def mostWords(sentences):
max_words = 0
for sentence in sentences:
word_count = len(sentence.split())
max_words = max(max_words, word_count)
return max_words
解释:
-
sentence.split()
:通过空格将句子分割成单词,并返回一个单词列表。 -
len(sentence.split())
:计算该句子中单词的数量。 -
使用
max(max_words, word_count)
来更新最大单词数。
示例:
sentences = ["I am happy", "This is a test sentence", "Hello world"]
print(mostWords(sentences)) # 输出:4
在上面的示例中,第二个句子 "This is a test sentence"
包含 5 个单词,是最多的,因此返回的结果是 5。