1816. 截斷句子
句子 是一個單詞列表,列表中的單詞之間用單個空格隔開,且不存在前導或尾隨空格。每個單詞僅由大小寫英文字母組成(不含標點符號)。
例如,“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 中的單詞之間由單個空格隔開
- 不存在前導或尾隨空格
解題思路
s 中的單詞之間由單個空格隔開,因此我們需要遍歷s中的每一個字符,當遇到空格時直接跳過,當遇到字母時,將字母后面連續的沒有被空格分隔開的字符全部遍歷一遍,直到遇到空格時結束遍歷,則說明我們已經找到了一個單詞,如此類推,直到我們找到了題目要求的k個單詞以后,跳出循環,并且記錄下當前的下標,該下標之前的字符串就是我們需要截斷的字符串,然后將該子串返回。
代碼
class Solution {
public:string truncateSentence(string s, int k) {int i=0;while (k>0){if (isalpha(s[i])){while (isalpha(s[i]))i++;k--;}else i++;}return s.substr(0,i);}
};