### Truncate Sentence LeetCode Solution - The Coding Shala

Home >> LeetCode >> Truncate Sentence

In this post, we will learn how to solve LeetCode's Truncate Sentence problem and will implement its solution in Java.

## Truncate Sentence Problem

You are given a sentence s​​​​​​ and an integer k​​​​​​. You want to truncate s​​​​​​ such that it contains only the first k​​​​​​ words. Return s​​​​​​ after truncating it.

Example 1:
Input: s = "Hello how are you Contestant", k = 4
Output: "Hello how are you"
Explanation:
The words in s are ["Hello", "how" "are", "you", "Contestant"].
The first 4 words are ["Hello", "how", "are", "you"].
Hence, you should return "Hello how are you".

Example 2:
Input: s = "chopper is not a tanuki", k = 5
Output: "chopper is not a tanuki"

Practice this problem on LeetCode.

## LeetCode - Truncate Sentence Java Solution

Approach 1

First, convert the given string to an array then take the first k words and make a string and return.

Java Program:

```class Solution {
public String truncateSentence(String s, int k) {
// change string to array
String[] arr = s.split(" ");
StringBuilder sb = new StringBuilder();

//make string using k words
for(int i = 0; i < k; i++) {
sb.append(arr[i]+ " ");
}

//trim is used to remove last white space
return sb.toString().trim();
}
}
```

Approach 2

Using Java's in-built methods.

Java Program:

```class Solution {
public String truncateSentence(String s, int k) {
return String.join(" " , Arrays.copyOfRange(s.split(" "), 0, k));
}
}
```

Approach 3

Not using split. We can count white space and return string according to that. This program is performed better than the two above.

Java Program:

```class Solution {
public String truncateSentence(String s, int k) {
int spaceCount = 0;
int index = 0;
while(index < s.length()) {
if(s.charAt(index) == ' ') spaceCount++;
if(spaceCount == k) break;
index++;
}
return s.substring(0, index);
}
}
```

Other Posts You May Like