Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
linear time:
1. go through the string detect whether the place is ' ' if not append the char to word
2 if the place is ' ' and word is not "" append the word to res
3. go to the end append the word if the word is not ""
reverse the res
4. do join.
class Solution:
# @param s, a string
# @return a string
def reverseWords(self, s):
i = 0
res = []
word = ''
while i < len(s):
if s[i] != ' ':
word += s[i]
elif s[i] == ' ' or i == len(s) - 1:
if word != "":
res.append(word)
word = ""
i += 1
if word != "":
res.append(word)
res.reverse()
return " ".join(res)
本文介绍了一种将输入字符串中的单词进行逆序排列的方法。举例来说,若输入为theskyisblue,则返回结果为blueisskythe。文章详细解释了算法步骤,并提供了一个Python实现示例。
550

被折叠的 条评论
为什么被折叠?



