A sentence is a list of words separated by spaces. Given a sentence s and an integer k, return the first k words of the sentence. If k is 0, return an empty string.
Split the sentence into words by spaces, take the first k words, and join them back with spaces. Handle the case where k is larger than the number of words (return the whole sentence) and k is 0 (return empty string).
Time complexity is O(n) for splitting and O(k) for joining. Space complexity is O(n) for the word array.
Example Input & Output
Example 1
Input
"single",1
Output
"single"
Explanation
Single word
Example 2
Input
"Hello how are you Contestant",4
Output
"Hello how are you"
Explanation
First 4 words
Example 3
Input
"a b c d e f",2
Output
"a b"
Explanation
First 2 words
Example 4
Input
"What is the solution",3
Output
"What is the"
Explanation
First 3 words
Example 5
Input
"one two three",0
Output
""
Explanation
Zero words
Algorithm Flow

Recommendation Algorithm Flow for Truncate Sentence
Solution Approach
Best Answers
java
class Solution {
public String solution(String s, int k) {
String[] w=s.split(" ",-1);
StringBuilder r=new StringBuilder();
for(int i=0;i<k&&i<w.length;i++){r.append(w[i]);if(i<k-1)r.append(' ');}
return r.toString();
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
