题目描述
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Clarification:
What constitutes a word?
A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
题目大意
输入一个字符串,逐单词逆转该字符串。
单词的组成?
由非空格的字符组成
输入字符串是否可能包含前导或者后缀空格?
可能。不过你逆转完毕的字符串中不应包含前导或者后缀空格。
两个单词之间包含多个空格怎么处理?
把它们合并成一个空格
解题思路
水题,略
Python代码如下:
class Solution:
# @param s, a string
# @return a string
def reverseWords(self, s):
words = s.split()
words.reverse()
return " ".join(words)
本文链接:http://bookshadow.com/weblog/2014/10/16/leetcode-reverse-words-string/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。