本题的要求是将一段英文句子中的单词进行倒置。
本题链接
Given an input string, reverse the string word by word.
For example,
Given s = “the sky is blue”,
return “blue is sky the”.
注意到本题的细节是将单词进行置换,而不是单纯将字符进行倒置。
做法其实并不难,就是找到单词的分隔符空格‘ ’和字符串结束符‘\0’,然后把单词取出,最后进行反向合并即可。
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
result = ""
words = s.split(" ")
for i in range(len(words)-1,-1,-1):
if words[i] != "":
result += words[i] + " "
return result[:-1]