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".

 

 1 class Solution {
 2 public:
 3     void reverseWords(string &s) {
 4         char c;
 5         int i,j,k;
 6         i = 0;
 7         while(s[i] == ' ')
 8          {
 9            s.erase(0,1);
10          }
11         int len = strlen(s.c_str());
12         j = len-1;
13         while (s[j] == ' ')
14         {
15             s.erase(j,1);
16             j--;
17         }
18         len = strlen(s.c_str());
19         i = 0;
20         j = len-1;
21         while (i < j)
22         {
23             c = s[i];
24             s[i] = s[j];
25             s[j] = c;
26             i++;
27             j--;
28         }
29         i = 0;
30         while (true)
31         {
32             if (s[i] == '\0')
33                 break;
34             while(s[i] == ' ')
35                 i++;
36             j = i;
37             while (s[j] != ' ' && s[j] != '\0')
38                 j++;
39             k = i;
40             i = j;
41             j--;
42             while (k < j)
43             {
44                 c = s[k];
45                 s[k] = s[j];
46                 s[j] = c;
47                 k++;
48                 j--;
49             }
50         }
51         for (i=1; i < len; i++)
52         {
53             if (s[i] == ' ' && s[i-1] == ' ')
54                {
55                    s.erase(i,1);
56                     len--;
57                     i--;
58                }
59         }
60     }
61 }; 

 

记得先处理前后和中间多余的空格。

 

 

posted @ 2014-10-19 01:42  george_cw  阅读(204)  评论(0编辑  收藏  举报