You are given a sentence s and an integer k. You need to truncate the sentence such that it contains only the first k words. Return the truncated sentence.
Example 1:
Input: s = "Hello how are you Contestant", k = 4
Output: "Hello how are you"
Example 2:
Input: s = "What is the solution to this problem", k = 4
Output: "What is the solution"
Example 3:
Input: s = "chopper is not a tanuki", k = 5
Output: "chopper is not a tanuki"
k be equal to or greater than the number of words in the sentence?
k will always be a positive integer less than or equal to the number of words in the sentence.split method to split the sentence s into a list of words based on spaces.k Words: Slice the list to get the first k words.join method to join the words back into a sentence with a single space as the delimiter.O(n) where n is the length of the sentence.O(k) where k is the number of words to be returned.O(k * m) where m is the average length of the words.Overall, the time complexity is O(n + k * m), which is typically linear in nature given the constraints.
def truncateSentence(s: str, k: int) -> str:
# Split the sentence into words
words = s.split()
# Take the first k words
truncated_words = words[:k]
# Join the words back into a sentence
truncated_sentence = ' '.join(truncated_words)
return truncated_sentence
# Test cases
print(truncateSentence("Hello how are you Contestant", 4)) # Expected: "Hello how are you"
print(truncateSentence("What is the solution to this problem", 4)) # Expected: "What is the solution"
print(truncateSentence("chopper is not a tanuki", 5)) # Expected: "chopper is not a tanuki"
This code effectively splits the sentence, takes the first k words, and then rejoins them into the truncated sentence.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?