1816. Truncate Sentence ¶ Time: $O(n)$ Space: $O(k)$ C++JavaPython 1 2 3 4 5 6 7 8 9class Solution { public: string truncateSentence(string s, int k) { for (int i = 0; i < s.length(); ++i) if (s[i] == ' ' && --k == 0) return s.substr(0, i); return s; } }; 1 2 3 4 5 6 7 8 9 10 11class Solution { public String truncateSentence(String s, int k) { String[] words = s.split(" "); String[] truncated = new String[k]; for (int i = 0; i < k; ++i) truncated[i] = words[i]; return String.join(" ", truncated); } } 1 2 3class Solution: def truncateSentence(self, s: str, k: int) -> str: return ' '.join(s.split()[:k])