class Solution:
def truncateSentence(self, s: str, k: int) -> str:
return ' '.join(s.split()[:k])
class Solution {
public:
string truncateSentence(string s, int k) {
int count = 0;
string result;
for (char c : s) {
if (c == ' ') {
count++;
if (count == k) break;
}
result += c;
}
return result;
}
};
class Solution {
public String truncateSentence(String s, int k) {
String[] words = s.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < k; i++) {
if (i > 0) sb.append(" ");
sb.append(words[i]);
}
return sb.toString();
}
}
var truncateSentence = function(s, k) {
return s.split(" ").slice(0, k).join(" ");
};
s
representing a sentence, and an integer k
. Your task is to return a truncated version of the sentence that contains only the first k
words. Words in the sentence are separated by single spaces, and there are no leading or trailing spaces. The output should be a string with exactly the first k
words from s
, separated by single spaces, and nothing more.
k
words efficiently and assemble them back into a valid sentence. We want to avoid unnecessary complexity and make use of language features to keep our solution clean and concise.
s
into a list (or array) of words using the space character as the separator. This gives us an ordered collection of all words in the sentence.k
words from this list. This can be done by slicing or iterating up to k
.This approach leverages the fact that splitting and joining strings are very efficient and readable operations in most languages. There is no need to manually count spaces or characters unless you want to avoid using built-in functions, but for clarity and speed, built-ins are preferred here.
Let's walk through an example:
s = "Hello how are you Contestant"
, k = 4
s
into words: ["Hello", "how", "are", "you", "Contestant"]
["Hello", "how", "are", "you"]
"Hello how are you"
"Hello how are you"
The process is straightforward and works for any valid input as described by the problem.
k
words have been found, the time complexity would still be O(n)
, where n
is the length of the string. Space complexity would also be O(n)
for storing the result.O(n)
time and space, since every character is processed once. Thus, time complexity is O(n)
and space complexity is O(n)
.
In both approaches, the bottleneck is processing the entire input string at least once, so O(n)
is optimal.
k
words from a sentence. By leveraging built-in string manipulation functions like split and join, we can solve the problem in a clean, readable, and efficient way. The solution is optimal in both time and space, and demonstrates the power of using standard library features for simple text processing tasks.