Given an input string, reverse the string word by word.
For example, Given s = "the sky is blue", return "blue is sky the".
the sky is blue
blue is sky the
click to show clarification.
C++: 直接扫描字符串把遇到的单词插入到deque的前面。扫描完把deque容器内的单词拼起来就可以。
class Solution { public: void reverseWords(string &s) { deque<string> ds; int b, i(0), len(s.size()); while (i < len) { while (i<len && s[i]==' ') ++i; if (i == len) break; b = i; while (i<len && s[i]!=' ') ++i; ds.push_front(s.substr(b, i-b)); } s = ""; if (ds.empty()) return; s += ds[0]; for (i=1; i<ds.size(); ++i) s += " " + ds[i]; } };
class Solution: # @param s, a string # @return a string def reverseWords(self, s): ss = s.split() ss.reverse() return " ".join(ss)