调试中...
调试中...
题目描述
题目描述
题解
题解
提交记录
提交记录
代码
代码
测试用例
测试用例
测试结果
测试结果
简单
相关标签
相关企业
提示

句子 是一个单词列表,列表中的单词之间用单个空格隔开,且不存在前导或尾随空格。每个单词仅由大小写英文字母组成(不含标点符号)。

  • 例如,"Hello World""HELLO""hello world hello world" 都是句子。

给你一个句子 s​​​​​​ 和一个整数 k​​​​​​ ,请你将 s​​ 截断 ​,​​​使截断后的句子仅含 k​​​​​​ 个单词。返回 截断 s​​​​​​ 后得到的句子

 

示例 1:

输入: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 中的单词之间由单个空格隔开
  • 不存在前导或尾随空格
通过次数
59K
提交次数
81K
通过率
72.8%

相关标签

相关企业

提示 1
It's easier to solve this problem on an array of strings so parse the string to an array of words

提示 2
After return the first k words as a sentence

评论 (0)

贡献者
© 2025 领扣网络(上海)有限公司
0 人在线
行 1,列 1
运行和提交代码需要登录
s =
"Hello how are you Contestant"
k =
4
Source