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.
click to show clarification.
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.
s思路: 1. 這道題見過多次了。先全部reverse,然后對每個單詞reverse。 2. 重點反而不是reverse,可以把reverse寫成一個函數;重點是找到每個單詞的開始結尾。可能有任意多個空格,導致不規則的情況,不規則的情況,我們一般用while來handle。
3.這道題還是比較復雜的,要求去掉所有冗余空格。現在這個方法比自己想到的方法簡單得多,而且好實現!自己原先想的方法是:對空格計數,數完然后一起刪;而別人家的代碼,看空格的坐標,如果i=0或i=n-1,以及看這個坐標左右位置是否有單詞決定是否刪除這個空格,即:一個一個的判斷,一個一個的刪除。就不用計數了,簡單! 4.這里面的邏輯是這樣的:如果對空格計數,尤其是在頭部和尾部的空格,不能用坐標判斷,那對句中的空格和句首尾的空格就要分開處理,增加復雜性。這種情況下,就可以嘗試不計數,而改用發現一個刪除一個。以后做題的時候,定制化,比如統計空格的個數,雖然道理上沒錯,但是代碼很繁復,還不如不去管這些信息,直接判斷一個空格是否合法反而簡單!也就是說,好的方法是實現起來容易,道理講得明白即可,沒有非那一種不可。思考的時候,不可以潛意識覺得那一種就絕對好或絕對差,更不能給某一種方法打標簽,這樣只會讓自己執著一種方法,反而不利于獨立自由之思考!
class Solution {public: void reverse(string&s,int begin,int end){ while(begin<end){ swap(s[begin],s[end]); begin++; end--; } } void reverseWords(string &s) { // int n=s.size(); reverse(s,0,n-1); int i=0,l=0,r=0; while(i<n){ if(s[i]==' '){ if(i>0&&i<n-1&&s[i-1]!=' '&&s[i+1]!=' '){ i++; l=i; r=i; }else{ s.erase(i,1);n--;//長度減一 } }else{ while(r<n&&s[r]!=' ') r++; reverse(s,l,r-1); i=r; } } }};新聞熱點
疑難解答