Leetcode刷題日記(2020.06.05):翻轉單詞順序

題目如下:

 

 

 

 分析:本體涉及到多個空格當成一個空格,因此我立刻想到了Python中的split()函數,在這裏首先普及下split()和split(' ')兩個函數的區別:

 1 s1 = "we are family"#中間一個空格
 2 s2 = "we  are  family"#中間兩個空格
 3 s3 = "we   are   family"#中間三個空格
 4 s4 = "we    are    family"#中間四個空格
 5 
 6 s1 = s1.split(" ")
 7 s2 = s2.split(" ")
 8 s3 = s3.split(" ")
 9 s4 = s4.split(" ")
10 
11 print(s1)#['we', 'are', 'family']
12 print(s2)#['we', '', 'are', '', 'family']
13 print(s3)#['we', '', '', 'are', '', '', 'family']
14 print(s4)#['we', '', '', '', 'are', '', '', '', 'family']
 1 s1 = "we are family"#中間一個空格
 2 s2 = "we  are  family"#中間兩個空格
 3 s3 = "we   are   family"#中間三個空格
 4 s4 = "we    are    family"#中間四個空格
 5 
 6 s1 = s1.split()
 7 s2 = s2.split()
 8 s3 = s3.split()
 9 s4 = s4.split()
10 
11 print(s1)#['we', 'are', 'family']
12 print(s2)#['we', 'are', 'family']
13 print(s3)#['we', 'are', 'family']
14 print(s4)#['we', 'are', 'family']

從以上我的例子我們得出結論:split()的時候,多個空格當成一個空格;split(' ')的時候,多個空格都要分割,每個空格分割出來空。

接下來我們迴歸到本體,其實思路很簡單,我們首先將這個字符串按照空格切分,然後呢,我們在藉助於列表中可以倒序的方法,一行代碼便能解決

代碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# @Time : 2020/6/5 15:06 

# @Author : ZFJ

# @File : 翻轉單詞順序.py 

# @Software: PyCharm
"""


class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        # 這邊我使用split(),便可以將多個空格看成是一個空格
        return ' '.join(s.strip().split()[::-1])


a = Solution().reverseWords(s='I am a student.')
print("反轉後的句子是:{}".format(a))

b = Solution().reverseWords(s="  hello world!  ")
print("反轉後的句子是:{}".format(b))

有人說,哎呀,我記得python中有個reverse()函數,我可以用嗎?答案是肯定的,那麼我們可以這麼寫,代碼如下:

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 """
 4 # @Time : 2020/6/5 15:06 
 5 
 6 # @Author : ZFJ
 7 
 8 # @File : 翻轉單詞順序.py 
 9 
10 # @Software: PyCharm
11 """
12 
13 
14 class Solution(object):
15     def reverseWords(self, s):
16         """
17         :type s: str
18         :rtype: str
19         """
20         # # 這邊我使用split(),便可以將多個空格看成是一個空格
21         # return ' '.join(s.strip().split()[::-1])
22         # 刪除首尾的空格
23         s = s.strip()
24         # 按照空格分隔字符串
25         strs = s.split()
26         # 使用reverse()翻轉單詞列表
27         strs.reverse()
28         # 拼接爲字符串並且返回
29         return ' '.join(strs)
30 
31 
32 a = Solution().reverseWords(s='I am a student.')
33 print("反轉後的句子是:{}".format(a))
34 
35 b = Solution().reverseWords(s="  hello world!  ")
36 print("反轉後的句子是:{}".format(b))

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章