LeetCode简单题之截断句子
題目
句子 是一個單詞列表,列表中的單詞之間用單個空格隔開,且不存在前導或尾隨空格。每個單詞僅由大小寫英文字母組成(不含標點符號)。
例如,“Hello World”、“HELLO” 和 “hello world hello world” 都是句子。
給你一個句子 s?????? 和一個整數(shù) 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 中單詞的數(shù)目]
s 僅由大小寫英文字母和空格組成
s 中的單詞之間由單個空格隔開
不存在前導或尾隨空格
來源:力扣(LeetCode)
解題思路
??遍歷句子,然后計算空格數(shù)量,如果在遍歷完成前空格數(shù)等于k,直接可以截斷句子,否則k大于句子中的單詞數(shù),返回原句。
class Solution:def truncateSentence(self, s: str, k: int) -> str:count=0for i in range(len(s)):if s[i]==' ':count+=1if count==k:breakreturn s[0:i] if i!=len(s)-1 else s
總結
以上是生活随笔為你收集整理的LeetCode简单题之截断句子的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode简单题之按键持续时间最长
- 下一篇: LeetCode简单题之统一一致字符串的