Similar Problems

Similar Problems not available

Maximum Number Of Words Found In Sentences - Leetcode Solution

Companies:

LeetCode:  Maximum Number Of Words Found In Sentences Leetcode Solution

Difficulty: Easy

Topics: string array  

Problem Statement

Given a string text consisting of multiple sentences, find the maximum number of words that can be present in any sentence in the text.

Solution

To solve this problem, we will follow the following steps:

  • Split the given string text into a list of sentences.
  • For each sentence, split it into a list of words and count the number of words.
  • Keep track of the maximum number of words found in any sentence so far.
  • Return the maximum number of words found in any sentence.

Let's implement this solution in Python:

def max_words(text): # Split the given string into a list of sentences. sentences = text.split('.')

# Initialize the maximum number of words found in any sentence to zero.
max_words = 0

# For each sentence, split it into a list of words and count the number of words.
for sentence in sentences:
    words = sentence.split()
    num_words = len(words)

    # Keep track of the maximum number of words found in any sentence so far.
    if num_words > max_words:
        max_words = num_words

# Return the maximum number of words found in any sentence.
return max_words

This function takes a string text as input and returns the maximum number of words found in any sentence in the text.

Let's test this function with some examples:

Example 1

text = "This is a test. Here is another test." print(max_words(text)) # Output: 4

Example 2

text = "Hello, how are you? I am fine, thank you!" print(max_words(text)) # Output: 5

Example 3

text = "This is a single sentence." print(max_words(text)) # Output: 4

In example 1, the maximum number of words present in any sentence is 4.

In example 2, the maximum number of words present in any sentence is 5.

In example 3, there is only one sentence, so the maximum number of words present in any sentence is equal to the number of words present in the sentence, i.e., 4.

Time Complexity

The time complexity of this solution is O(n), where n is the total number of characters in the input string. This is because we need to split the input string into sentences and then split each sentence into words, which takes linear time. We also need to iterate over all the sentences to count the number of words in each sentence, which again takes linear time. Therefore, the overall time complexity of this solution is O(n).

Space Complexity

The space complexity of this solution is O(n), where n is the total number of characters in the input string. This is because we need to store the input string and the sentences and words obtained after splitting the input string in memory. Therefore, the overall space complexity of this solution is O(n).

Maximum Number Of Words Found In Sentences Solution Code

1