句子 是一个单词列表,列表中的单词之间用单个空格隔开,且不存在前导或尾随空格。每个单词仅由大小写英文字母组成(不含标点符号)。
"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"
提示:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/truncate-sentence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
直接遍历字符串,由于既没有前导或尾随空格,且单词之间由单空格隔开,只需要在遍历的时候每次遇到空格就--k,直到k为0时输出下标,注意最后一个单词后面无空格,所以对于下标超出字符串长度的情况也需要--k。
时间复杂度O(n),空间复杂度O(1)。
class Solution { public: string truncateSentence(string s, int k) { int PosEnd = 0; for(; k > 0; ++PosEnd){ if(PosEnd == s.size() || s[PosEnd] == ' '){ --k; } } return PosEnd == s.size() ? s.substr(0, PosEnd) : s.substr(0, PosEnd - 1); } };