|
| 1 | +// Tags: String |
| 2 | +package com.leetcode.easy; |
| 3 | + |
| 4 | +public class TruncateSentence1816 { |
| 5 | + /** |
| 6 | + * Truncates the sentence to only contain the first k words. |
| 7 | + * |
| 8 | + * <p>A sentence is a list of words that are separated by a single space with no leading or trailing spaces. |
| 9 | + * This method splits the input string and reconstructs it using only the first k words.</p> |
| 10 | + * |
| 11 | + * <h3>Algorithm:</h3> |
| 12 | + * <ol> |
| 13 | + * <li>Split the input string by spaces to get all words</li> |
| 14 | + * <li>Iterate through the first k words and append them to a StringBuilder</li> |
| 15 | + * <li>Return the concatenated result as a String</li> |
| 16 | + * </ol> |
| 17 | + * |
| 18 | + * <h3>Time Complexity: O(n)</h3> |
| 19 | + * <ul> |
| 20 | + * <li><b>split() operation:</b> O(n) - Scans the entire input string of length n once to find spaces</li> |
| 21 | + * <li><b>For loop:</b> O(k) iterations × O(1) per iteration = O(k)</li> |
| 22 | + * <li><b>StringBuilder appends:</b> O(m) total where m is total characters in first k words (amortized O(1) per append)</li> |
| 23 | + * <li><b>toString() call:</b> O(m) to create the final String</li> |
| 24 | + * <li><b>Total:</b> O(n) + O(k) + O(m) = O(n) since k ≤ n and m ≤ n</li> |
| 25 | + * </ul> |
| 26 | + * |
| 27 | + * <h3>Space Complexity: O(n)</h3> |
| 28 | + * <ul> |
| 29 | + * <li><b>words array:</b> O(n) - Stores all word references and substring objects from split</li> |
| 30 | + * <li><b>StringBuilder:</b> O(m) - Internal buffer stores up to m characters (first k words + spaces)</li> |
| 31 | + * <li><b>Result String:</b> O(m) - New String object created from StringBuilder</li> |
| 32 | + * <li><b>Total:</b> O(n) dominant, as the split array uses O(n) space regardless of k</li> |
| 33 | + * </ul> |
| 34 | + * |
| 35 | + * <h3>Example:</h3> |
| 36 | + * <pre> |
| 37 | + * Input: s = "Hello how are you", k = 2 |
| 38 | + * Output: "Hello how" |
| 39 | + * Explanation: Returns only the first 2 words separated by a space |
| 40 | + * </pre> |
| 41 | + * |
| 42 | + * @param s the input sentence consisting of words separated by single spaces (length ≥ 1) |
| 43 | + * @param k the number of words to keep from the beginning (1 ≤ k ≤ number of words in s) |
| 44 | + * @return a new string containing only the first k words separated by spaces |
| 45 | + */ |
| 46 | + public String truncateSentence(String s, int k) { |
| 47 | + String[] words = s.split(" "); |
| 48 | + StringBuilder res = new StringBuilder(); |
| 49 | + for (int i = 0; i < k; i++) { |
| 50 | + if (i > 0) res.append(" "); |
| 51 | + res.append(words[i]); |
| 52 | + } |
| 53 | + return res.toString(); |
| 54 | + } |
| 55 | +} |
0 commit comments