• Home
  • Finding the longest n interspace substring – Python

Finding the longest n interspace substring – Python

To find the longest n-interspace substring in a string in Python, you can use the following approach:

  1. Split the string into a list of words using the split() method.
  2. Initialize a variable max_len to store the maximum length of the substring found so far.
  3. Iterate through the list of words and for each word, calculate the length of the n-interspace substring formed by including that word and the next n-1 words.
  4. Update the max_len variable if the length of the current n-interspace substring is greater than the maximum length found so far.
  5. Return the maximum length of the n-interspace substring found.

Here is an example of how this can be implemented:

def longest_n_interspace_substring(s, n):
words = s.split()
max_len = 0
for i in range(len(words) - n + 1):
substring = " ".join(words[i:i+n])
max_len = max(max_len, len(substring))
return max_len

# Test the function
s = "This is a sample string with multiple words"
n = 3
print(longest_n_interspace_substring(s, n)) # prints "sample string with" (length = 20)

This approach has a time complexity of O(n), where n is the number of words in the string.