Leetcode - Python - Reverse Words in a String

Leetcode题目:

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

分析:如果直接用Python内置的函数的话,思路非常简单。首先,将输入string用split()函数分开,获得一个string list,然后再将它翻转reverse(),之后再按顺序接起来,string element之间隔上一个space。

实现代码:

class Solution:
    # @param s, a string
    # @return a string
    def reverseWords(self, s):
        string_l = s.split()
        string_l.reverse()
        if not string_l:
            return ""
        new_string =string_l[0]
        l = len(string_l)
        for i in range(1,l):
            new_string = new_string +" "+string_l[i]
        return new_string
实现时出现得问题:

在一开始分离string,获得string list时,我采用了以下一行代码:

string_l = s.split().reverse()

后来改进成:

       string_l = s.split()
        string_l.reverse()

为什么第一种写法不对呢?因为reverse()在python里面是一个没有返回值的函数。它只是改变string本身。由此在第一种写法,string_l一直为None. 

写题写多了,后来慢慢觉得,了解一种语言的特性有些时候会成为成败的关键。






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值