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.
写题写多了,后来慢慢觉得,了解一种语言的特性有些时候会成为成败的关键。