A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of only uppercase and lowercase English letters (no punctuation).
- For example,
"Hello World"
,"HELLO"
, and"hello world hello world"
are all sentences.
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.
LeetCode Problem - 1816
class Solution {
public String truncateSentence(String s, int k) {
// Split the input sentence into an array of words
String[] array = s.split(" ");
// Create a StringBuilder to build the truncated sentence
StringBuilder sb = new StringBuilder();
// Iterate through the words up to k
for (int i = 0; i < k; i++) {
// Append each word to the StringBuilder
if (i != k - 1) {
sb.append(array[i]).append(" ");
} else {
sb.append(array[i]);
}
}
// Convert the StringBuilder to a string and return
return sb.toString();
}
}