[leetcode] Reverse Words in a String

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 class Solution
 2 {
 3 public:
 4   void reverseWords(string &s)
 5   {
 6     string temp = "", s1 = "";
 7     for(int i=s.size()-1; i>=0;)
 8     {
 9       if(s[i] == ' ' || i == 0) 
10       {
11         if(i == 0 && s.size()>0 && s[i+1] != ' ' && s[i] != ' ')
12           temp = s[i--] + temp;
13         else if(i == 0 && s[i] != ' ')
14           temp = s[i--];
15 
16         while(s[i] == ' ') i--;
17 
18         if(s1 == "")
19           s1 = temp;
20         else
21           s1 += " " + temp;
22 
23         temp = ""; 
24       }
25       else if(s[i] != ' ')
26         temp = s[i--] + temp;
27     }
28 
29     s = s1;
30   }
31 };

 

posted @ 2015-03-05 13:54  imKirin  阅读(134)  评论(0编辑  收藏  举报