**输入:** s = "Hello how are you Contestant", k = 4
**输出:** "Hello how are you"
**解释:**
s 中的单词为 ["Hello", "how" "are", "you", "Contestant"]
前 4 个单词为 ["Hello", "how", "are", "you"]
因此,应当返回 "Hello how are you"
示例 2:
**输入:** s = "What is the solution to this problem", k = 4
**输出:** "What is the solution"
**解释:**
s 中的单词为 ["What", "is" "the", "solution", "to", "this", "problem"]
前 4 个单词为 ["What", "is", "the", "solution"]
因此,应当返回 "What is the solution"
示例 3:
**输入:** s = "chopper is not a tanuki", k = 5
**输出:** "chopper is not a tanuki"
提示:
1 <= s.length <= 500
k 的取值范围是 [1, s 中单词的数目]
s 仅由大小写英文字母和空格组成
s 中的单词之间由单个空格隔开
不存在前导或尾随空格
方法一:遍历
思路与算法
由题意可知,除了最后一个单词,每个单词后面都跟随一个空格。因此我们可以通过统计空格与句子结尾的数目来统计单词数 count。当 count}=\textit{k 时,将当前的下标记录到 end,返回句子 s 在 end 处截断的句子。
代码
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
char * truncateSentence(char * s, int k){ int n = strlen(s); int end = 0, count = 0; for (int i = 1; i <= n; i++) { if (i == n || s[i] == ' ') { count++; if (count == k) { end = i; break; } } } s[end] = '\0'; return s; }
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { public: string truncateSentence(string s, int k){ int n = s.size(); int end = 0, count = 0; for (int i = 1; i <= n; i++) { if (i == n || s[i] == ' ') { count++; if (count == k) { end = i; break; } } } return s.substr(0, end); } };
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public String truncateSentence(String s, int k) { intn= s.length(); intend=0, count = 0; for (inti=1; i <= n; i++) { if (i == n || s.charAt(i) == ' ') { count++; if (count == k) { end = i; break; } } } return s.substring(0, end); } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
publicclassSolution { publicstringTruncateSentence(string s, int k) { int n = s.Length; int end = 0, count = 0; for (int i = 1; i <= n; i++) { if (i == n || s[i] == ' ') { count++; if (count == k) { end = i; break; } } } return s.Substring(0, end); } }
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13
functruncateSentence(s string, k int)string { n, end, count := len(s), 0, 0 for i := 1; i <= n; i++ { if i == n || s[i] == ' ' { count++ if count == k { end = i break } } } return s[:end] }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
var truncateSentence = function(s, k) { const n = s.length; let end = 0, count = 0; for (let i = 1; i <= n; i++) { if (i === n || s[i] === ' ') { count++; if (count === k) { end = i; break; } } } return s.slice(0, end); };
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10
classSolution: deftruncateSentence(self, s: str, k: int) -> str: n, end, count = len(s), 0, 0 for i inrange(1, n + 1): if i == n or s[i] == ' ': count += 1 if count == k: end = i break return s[:end]