标签:
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 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 };
Reverse Words in a String--not finished yet
标签:
原文地址:http://www.cnblogs.com/amazingzoe/p/5186926.html