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))
原文地址:https://www.cnblogs.com/ZFJ1094038955/p/13049991.html