Truncate Sentence
Problem​
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. A word is defined as a substring consisting of non-space characters only.
Examples​
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"
Constraints​
1 <= s.length <= 500
k
is in the range[1, the number of words in s]
s
consists of only lowercase and uppercase English letters and spaces.- The words in
s
are separated by a single space. - There are no leading or trailing spaces.
Approach​
To solve this problem, we can follow a straightforward approach:
- Split the sentence
s
into a list of words. - Extract the first
k
words from this list. - Join these
k
words back into a string with spaces.
Solution​
Python​
class Solution:
def truncateSentence(self, s: str, k: int) -> str:
# Split the sentence into words
words = s.split()
# Get the first k words
truncated_words = words[:k]
# Join the first k words into a string
truncated_sentence = " ".join(truncated_words)
return truncated_sentence