Reverse Words in a String--not finished yet

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.
 
Analyse: For my first thought, I will reverse the string first, then every word in the string has been reversed. Then I find each word, and reverse them. Space complexity is O(1). Time complexity is O(1). 
 1 class Solution {
 2 public:
 3     void reverse(string& s, int start, int end){
 4     if(start >= end) return;
 5     for(int i = start, j = end; i < j; i++, j--)
 6         swap(s[i], s[j]);
 7 }
 8 
 9 
10 void reverseWords(string& s) {
11     if(s.size() < 2) return;
12     
13     //first inverse the string
14     //every word has been reversed
15     reverse(s, 0, s.size() - 1);
16     
17     //for each word, reverse the word back
18     int start = 0;
19     for(int i = 0; i < s.size(); i++){
20         while(s[i] != ' ') i++;
21         if(i >= s.size()) i = s.size();
22         reverse(s, start, i - 1);
23         start = i + 1;
24     }
25     
26     for(int i = 0; i < s.size(); i++)
27         cout<<s[i];
28     
29 }
30 };

 

posted @ 2016-02-12 11:40  amazingzoe  阅读(134)  评论(0编辑  收藏  举报