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)
151. Reverse Words in a String Leetcode Python
原文地址:http://blog.csdn.net/hyperbolechi/article/details/44733781