Reverse Words in a String
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.
解題思路:
1、若用C#實現,非常簡單,用字符串的split函數,將非空的子串倒著連接起來即可。
2、C++似乎沒有split函數,需要我們自己實現一下,返回vector
3、可以只掃描一次字符串。下面是代碼。有幾個特殊情況需要考慮(1)可能會有多個空格符(2)可能沒有空格符
class Solution { public: void reverseWords(string &s) { string result=""; int len = s.length(); string word=""; for(int i=0; i