Similar Problems

Similar Problems not available

Truncate Sentence - Leetcode Solution

Companies:

LeetCode:  Truncate Sentence Leetcode Solution

Difficulty: Easy

Topics: string array  

The Truncate Sentence problem on LeetCode is a simple string manipulation problem. The problem statement is as follows:

Given a string s and an integer k, truncate the sentence represented by s to a length of k characters (including spaces) and return the truncated sentence.

For example, if s = "Hello world how are you doing", and k = 12, the answer would be "Hello world".

To solve this problem, we need to split the given sentence into individual words, iterate over the words until we reach the length k, and join them back into a string. Here is the step-by-step solution:

Step 1: Split the sentence into individual words

We can split the sentence into individual words using the string method split(). We can split on space character (' ') to get the list of words.

words = s.split(' ')

Step 2: Iterate over the words until we reach the length k

We need to keep track of the length of the truncated sentence at each iteration and stop when we reach the length k. We can use a counter variable to keep track of the length.

counter = 0 for i in range(len(words)): counter += len(words[i]) if counter > k: break

Step 3: Join the words back into a string

Once we have the list of words, we can join them back into a string using the string method join(). We only need to join the words up to the point where we reached the length k.

truncated_words = words[:i] truncated_sentence = ' '.join(truncated_words)

Finally, we return the truncated sentence.

Complete Solution

Here is the complete solution in Python:

def truncateSentence(s: str, k: int) -> str: words = s.split(' ') counter = 0 for i in range(len(words)): counter += len(words[i]) if counter > k: break truncated_words = words[:i] truncated_sentence = ' '.join(truncated_words) return truncated_sentence

This solution has a time complexity of O(n), where n is the length of the sentence.

Truncate Sentence Solution Code

1