Class Solution

java.lang.Object
g1801_1900.s1816_truncate_sentence.Solution

public class Solution extends Object
1816 - Truncate Sentence.<p>Easy</p> <p>A <strong>sentence</strong> is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of <strong>only</strong> uppercase and lowercase English letters (no punctuation).</p> <ul> <li>For example, <code>&quot;Hello World&quot;</code>, <code>&quot;HELLO&quot;</code>, and <code>&quot;hello world hello world&quot;</code> are all sentences.</li> </ul> <p>You are given a sentence <code>s</code> and an integer <code>k</code>. You want to <strong>truncate</strong> <code>s</code> such that it contains only the <strong>first</strong> <code>k</code> words. Return <code>s</code>_ after <strong>truncating</strong> it._</p> <p><strong>Example 1:</strong></p> <p><strong>Input:</strong> s = &ldquo;Hello how are you Contestant&rdquo;, k = 4</p> <p><strong>Output:</strong> &ldquo;Hello how are you&rdquo;</p> <p><strong>Explanation:</strong></p> <p>The words in s are [&ldquo;Hello&rdquo;, &ldquo;how&rdquo; &ldquo;are&rdquo;, &ldquo;you&rdquo;, &ldquo;Contestant&rdquo;].</p> <p>The first 4 words are [&ldquo;Hello&rdquo;, &ldquo;how&rdquo;, &ldquo;are&rdquo;, &ldquo;you&rdquo;].</p> <p>Hence, you should return &ldquo;Hello how are you&rdquo;.</p> <p><strong>Example 2:</strong></p> <p><strong>Input:</strong> s = &ldquo;What is the solution to this problem&rdquo;, k = 4</p> <p><strong>Output:</strong> &ldquo;What is the solution&rdquo;</p> <p><strong>Explanation:</strong></p> <p>The words in s are [&ldquo;What&rdquo;, &ldquo;is&rdquo; &ldquo;the&rdquo;, &ldquo;solution&rdquo;, &ldquo;to&rdquo;, &ldquo;this&rdquo;, &ldquo;problem&rdquo;].</p> <p>The first 4 words are [&ldquo;What&rdquo;, &ldquo;is&rdquo;, &ldquo;the&rdquo;, &ldquo;solution&rdquo;].</p> <p>Hence, you should return &ldquo;What is the solution&rdquo;.</p> <p><strong>Example 3:</strong></p> <p><strong>Input:</strong> s = &ldquo;chopper is not a tanuki&rdquo;, k = 5</p> <p><strong>Output:</strong> &ldquo;chopper is not a tanuki&rdquo;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 <= s.length <= 500</code></li> <li><code>k</code> is in the range <code>[1, the number of words in s]</code>.</li> <li><code>s</code> consist of only lowercase and uppercase English letters and spaces.</li> <li>The words in <code>s</code> are separated by a single space.</li> <li>There are no leading or trailing spaces.</li> </ul>
  • Constructor Details

    • Solution

      public Solution()
  • Method Details

    • truncateSentence

      public String truncateSentence(String s, int k)