Reverse Words in a String

2014.3.18 03:09

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

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.

Solution:

  Reverse the whole string first, then reverse every single word. Redundant spaces must be skipped.

  Total time complexity is O(n). Space complexity is O(1).

Accepted code:

 1 // 1TLE, 1AC, using another char[] is unnecessary. Don't miss '++i' or '++j'.
 2 class Solution {
 3 public:
 4     void reverseWords(string &s) {
 5         int i, j;
 6         int len;
 7         int offset;
 8         
 9         // remove trailing spaces
10         while (s.length() > 0 && s[s.length() - 1] == ' ') {
11             s.pop_back();
12         }
13         len = (int)s.length();
14         if (len == 0) {
15             return;
16         }
17         
18         // remove leading spaces
19         i = 0;
20         while (i < len && s[i] == ' ') {
21             ++i;
22         }
23         s = s.substr(i, len - i);
24         len = (int)s.length();
25         
26         // reverse the whole string
27         reverse(s, 0, len - 1);
28         // reverse every word
29         i = 0;
30         while (i < len) {
31             j = i;
32             while (j < len && s[j] != ' ') {
33                 ++j;
34             }
35             reverse(s, i, j - 1);
36             i = j;
37             while (i < len && s[i] == ' ') {
38                 ++i;
39             }
40         }
41         
42         // remove redundant spaces between words
43         offset = 0;
44         i = 0;
45         while (true) {
46             j = i;
47             while (j < len && s[j] != ' ') {
48                 s[j - offset] = s[j];
49                 ++j;
50             }
51             i = j;
52             if (i == len) {
53                 break;
54             }
55             s[i - offset] = s[i];
56             ++i;
57             while (i < len && s[i] == ' ') {
58                 ++i;
59                 ++offset;
60             }
61         }
62         
63         while (offset > 0) {
64             s.pop_back();
65             --offset;
66         }
67     }
68 private:
69     void reverse(string &s, int ll, int rr) {
70         int i;
71         char ch;
72         
73         for (i = ll; i < ll + rr - i; ++i) {
74             ch = s[i];
75             s[i] = s[ll + rr - i];
76             s[ll + rr - i] = ch;
77         }
78     }
79 };

 

 posted on 2014-03-18 03:13  zhuli19901106  阅读(227)  评论(0编辑  收藏  举报