Problem Description
Explanation:
To solve this problem, we can split the input sentence s
into words using the space character as the delimiter. Then we can take the first k
words and concatenate them back together with a space between each word to form the truncated sentence.
Algorithm:
- Split the input sentence
s
into individual words using the space character as the delimiter. - Take the first
k
words from the list of words. - Join these
k
words back together with a space between each word to form the truncated sentence. - Return the truncated sentence.
Time Complexity:
The time complexity of this algorithm is O(n), where n is the length of the input sentence s
.
Space Complexity:
The space complexity of this algorithm is O(n), where n is the length of the input sentence s
.
:
Solutions
class Solution {
public String truncateSentence(String s, int k) {
String[] words = s.split(" ");
StringBuilder truncated = new StringBuilder();
for (int i = 0; i < k; i++) {
truncated.append(words[i]);
if (i < k - 1) {
truncated.append(" ");
}
}
return truncated.toString();
}
}
Loading editor...