当前位置:网站首页><No. 8> 1816. Truncate sentences (simple)

<No. 8> 1816. Truncate sentences (simple)

2022-07-07 12:00:00 Smoked Luoting purple Pavilion

Catalog

Title Description :

 Python Realization :


Title Description :

The sentence It's a list of words , Words in the list are separated by a single space , And there are no leading or trailing spaces . Each word is made up of English letters in upper and lower case only ( No punctuation ).

for example ,"Hello World""HELLO" and "hello world hello world" It's all sentences .

Here is a sentence for you s​​​​​​ And an integer k​​​​​​ , Would you please s​​ truncation ​,​​​ send truncation The following sentence contains only front k​​​​​​ Word . return truncation s​​​​​​ After the sentence .

 Python Realization :

class Solution(object):
    def truncateSentence(self, s, k):
        """
        :type s: str
        :type k: int
        :rtype: str
        """
        list_num = []
        list_num = s.split(" ") # Split the original string by spaces 
        list_final = []
        for i in range (k):
            list_final.append(list_num[i])
        return " ".join(list_final) # take list convert to str

In one line :

class Solution(object):
    def truncateSentence(self, s, k):
        """
        :type s: str
        :type k: int
        :rtype: str
        """

        return " ".join(s.split(" ")[:k])

原网站

版权声明
本文为[Smoked Luoting purple Pavilion]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071002352978.html