当前位置:网站首页>The maximum number of words in the sentence of leetcode simple question

The maximum number of words in the sentence of leetcode simple question

2022-07-06 15:07:00 ·Starry Sea

subject

One The sentence By some word And a single space between them , There will be no extra spaces at the beginning and end of the sentence .
Here's an array of strings sentences , among sentences[i] Represents a single The sentence .
Please return to a single sentence The maximum number of words .
Example 1:
Input :sentences = [“alice and bob love leetcode”, “i think so too”, “this is great thanks very much”]
Output :6
explain :

  • The first sentence “alice and bob love leetcode” All in all 5 Word .
  • The second sentence “i think so too” All in all 4 Word .
  • The third sentence “this is great thanks very much” All in all 6 Word .
    therefore , The third sentence has the largest number of words in a single sentence , All in all 6 Word .
    Example 2:
    Input :sentences = [“please wait”, “continue to fight”, “continue to win”]
    Output :3
    explain : There may be more than one sentence with the same number of words .
    In this case , The second sentence and the third sentence ( Bold italics ) There are the same number of words .
    Tips :
    1 <= sentences.length <= 100
    1 <= sentences[i].length <= 100
    sentences[i] Only lowercase letters and ’ ’ .
    sentences[i] There are no spaces at the beginning and end of .
    sentences[i] All words in are separated by a single space .
    source : Power button (LeetCode)

Their thinking

   Because in the sentence given by the title , Every sentence is very neat , So count the number of words in each sentence , Just count the number of spaces .

class Solution:
    def mostWordsFound(self, sentences: List[str]) -> int:
        MAX=0
        for i in sentences:
            count=i.count(' ')
            if MAX<count:
                MAX=count
        return MAX+1

 Insert picture description here

原网站

版权声明
本文为[·Starry Sea]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131327152763.html