|
| 1 | +### 题目描述 |
| 2 | + |
| 3 | +这是 LeetCode 上的 **[1816. 截断句子](https://leetcode-cn.com/problems/truncate-sentence/solution/gong-shui-san-xie-jian-dan-zi-fu-chuan-m-l7gu/)** ,难度为 **简单**。 |
| 4 | + |
| 5 | +Tag : 「模拟」 |
| 6 | + |
| 7 | + |
| 8 | + |
| 9 | +句子 是一个单词列表,列表中的单词之间用单个空格隔开,且不存在前导或尾随空格。 |
| 10 | + |
| 11 | +每个单词仅由大小写英文字母组成(不含标点符号)。 |
| 12 | + |
| 13 | +例如,`"Hello World"`、`"HELLO"` 和 `"hello world hello world"` 都是句子。 |
| 14 | +给你一个句子 `s` 和一个整数 `k` ,请你将 `s` 截断 ,使截断后的句子仅含 前 `k` 个单词。返回 截断 `s` 后得到的句子。 |
| 15 | + |
| 16 | +示例 1: |
| 17 | +``` |
| 18 | +输入:s = "Hello how are you Contestant", k = 4 |
| 19 | +
|
| 20 | +输出:"Hello how are you" |
| 21 | +
|
| 22 | +解释: |
| 23 | +s 中的单词为 ["Hello", "how" "are", "you", "Contestant"] |
| 24 | +前 4 个单词为 ["Hello", "how", "are", "you"] |
| 25 | +因此,应当返回 "Hello how are you" |
| 26 | +``` |
| 27 | +示例 2: |
| 28 | +``` |
| 29 | +输入:s = "What is the solution to this problem", k = 4 |
| 30 | +
|
| 31 | +输出:"What is the solution" |
| 32 | +
|
| 33 | +解释: |
| 34 | +s 中的单词为 ["What", "is" "the", "solution", "to", "this", "problem"] |
| 35 | +前 4 个单词为 ["What", "is", "the", "solution"] |
| 36 | +因此,应当返回 "What is the solution" |
| 37 | +``` |
| 38 | +示例 3: |
| 39 | +``` |
| 40 | +输入:s = "chopper is not a tanuki", k = 5 |
| 41 | +
|
| 42 | +输出:"chopper is not a tanuki" |
| 43 | +``` |
| 44 | + |
| 45 | +提示: |
| 46 | +* `1 <= s.length <= 500` |
| 47 | +* `k` 的取值范围是 `[1, s 中单词的数目]` |
| 48 | +* `s` 仅由大小写英文字母和空格组成 |
| 49 | +* `s` 中的单词之间由单个空格隔开 |
| 50 | +* 不存在前导或尾随空格 |
| 51 | + |
| 52 | +--- |
| 53 | + |
| 54 | +### 模拟 |
| 55 | + |
| 56 | +根据题意进行模拟,在拼接答案时对「空格」进行计数即可。 |
| 57 | + |
| 58 | +代码: |
| 59 | +```Java |
| 60 | +class Solution { |
| 61 | + public String truncateSentence(String s, int k) { |
| 62 | + StringBuilder sb = new StringBuilder(); |
| 63 | + int n = s.length(); |
| 64 | + for (int i = 0, cnt = 0; i < n && cnt < k; i++) { |
| 65 | + char c = s.charAt(i); |
| 66 | + if (c == ' ') cnt++; |
| 67 | + if (cnt < k) sb.append(c); |
| 68 | + } |
| 69 | + return sb.toString(); |
| 70 | + } |
| 71 | +} |
| 72 | +``` |
| 73 | +* 时间复杂度:$O(n)$ |
| 74 | +* 空间复杂度:$O(n)$ |
| 75 | + |
| 76 | +--- |
| 77 | + |
| 78 | +### 最后 |
| 79 | + |
| 80 | +这是我们「刷穿 LeetCode」系列文章的第 `No.1816` 篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。 |
| 81 | + |
| 82 | +在这个系列文章里面,除了讲解解题思路以外,还会尽可能给出最为简洁的代码。如果涉及通解还会相应的代码模板。 |
| 83 | + |
| 84 | +为了方便各位同学能够电脑上进行调试和提交代码,我建立了相关的仓库:https://github.com/SharingSource/LogicStack-LeetCode 。 |
| 85 | + |
| 86 | +在仓库地址里,你可以看到系列文章的题解链接、系列文章的相应代码、LeetCode 原题链接和其他优选题解。 |
| 87 | + |
0 commit comments