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).
"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.
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 = "What is the solution to this problem", k = 4 Output: "What is the solution" Explanation: The words in s are ["What", "is" "the", "solution", "to", "this", "problem"]. The first 4 words are ["What", "is", "the", "solution"]. Hence, you should return "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
consist of only lowercase and uppercase English letters and spaces.s
are separated by a single space.The problem asks to truncate a given sentence s
to contain only the first k
words. The solution involves iterating through the sentence and counting the spaces to determine the end of the k
-th word.
The most efficient approach is to leverage the built-in string manipulation functions in each programming language. The core idea is to:
Split the sentence into words: This is done using the split()
method (or equivalent) which splits the string at each space character, resulting in a list or array of words.
Take the first k
words: We slice the array of words to keep only the first k
elements. This efficiently extracts the desired portion of the sentence.
Join the words back together: The sliced array of words is joined back into a string using the join()
method (or equivalent), with a space character as the separator to reconstruct the truncated sentence.
The time complexity of this approach is dominated by the split()
and join()
operations. These operations typically have a linear time complexity, O(n), where n is the length of the string s
. Therefore, the overall time complexity is O(n).
The space complexity depends on the size of the intermediate array of words. In the worst-case scenario (where all characters are letters except for spaces between words), the array size is proportional to the number of words. The space required for the final truncated sentence is also proportional to the number of words (or the length of the string). Therefore, the overall space complexity is O(n) in the worst case. In many cases where k is smaller than the total words, the space complexity is better than O(n).
The following code snippets demonstrate the solution using different programming languages:
class Solution:
def truncateSentence(self, s: str, k: int) -> str:
words = s.split()
return " ".join(words[:k])
class Solution {
public String truncateSentence(String s, int k) {
String[] words = s.split(" ");
StringBuilder result = new StringBuilder();
for (int i = 0; i < k; i++) {
result.append(words[i]);
if (i < k - 1) {
result.append(" ");
}
}
return result.toString();
}
}
#include <string>
#include <sstream>
#include <vector>
class Solution {
public:
string truncateSentence(string s, int k) {
stringstream ss(s);
string word;
vector<string> words;
while (ss >> word) {
words.push_back(word);
}
string result = "";
for (int i = 0; i < k; ++i) {
result += words[i];
if (i < k - 1) {
result += " ";
}
}
return result;
}
};
/**
* @param {string} s
* @param {number} k
* @return {string}
*/
var truncateSentence = function(s, k) {
const words = s.split(' ');
return words.slice(0, k).join(' ');
};
func truncateSentence(s string, k int) string {
words := strings.Split(s, " ")
return strings.Join(words[:k], " ")
}
These code examples all follow the same basic approach: split, slice, and join. They demonstrate the efficiency and readability of this solution. Note that the choice of using StringBuilder
in Java or string concatenation in other languages is a matter of optimization. For smaller strings, it might not have a big impact. For very large strings, StringBuilder
is generally more efficient in Java because it avoids repeated string creation.