字符串中的单词逆序——python2

实现将字符串的单词逆序。例:

input:"Let's take LeetCode contest"
output:"s'teL ekat edoCteeL tsetnoc"
 代码如下:

class Solution(object):
    def reverseWords(self, s):
        sList=s.split();res=[]
        for w in sList:
            w=list(w)
            if len(w)%2==0:
                sw=len(w)/2
            else:sw=(len(w)-1)/2
            for i in range(sw):
                w[i],w[len(w)-i-1]=w[len(w)-i-1],w[i]
            res.append(''.join(w))
        return ' '.join(res)
s=Solution()
print s.reverseWords("Let's take LeetCode contest")
#补充:下面是更简洁的表示
class Solution(object):
    def reverseWords(self, s):
        return ' '.join(x[::-1] for x in s.split())
        
s=Solution()
print s.reverseWords("Let's take LeetCode contest")


你可能感兴趣的:(字符串中的单词逆序——python2)