Skip to content

1816. Truncate Sentence 👍

  • Time: $O(n)$
  • Space: $O(k)$
1
2
3
4
5
6
7
8
9
class 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
11
class 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
3
class Solution:
  def truncateSentence(self, s: str, k: int) -> str:
    return ' '.join(s.split()[:k])