标签:
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.
String
writePos 标记合适的位置,也就是将要写入的位置。第四部:改变字符串大小
另外,我们在最后压入了一个space,是为了最后的word可以统一处理。
if( writePos > 0) //remove the latest space s.resize(writePos - 1); else s.resize(0);//the str only contains space
总之,此题是一道好体,题小乾坤大,很多细节需要处理。
class Solution { private: void reverseWord(string &s, int left, int right) { char tmp; while(left < right) { tmp = s[left]; s[left] = s[right]; s[right] = tmp; left++; right--; } } public: void reverseWords(string &s) { if(s.size() == 0) return; //reverse all words reverseWord(s, 0, s.size() - 1); s.push_back(‘ ‘);//inorder to handler the latest part int size = s.size(); int writePos = 0;//position which will be written int left = 0, right = 0; for(int i = 0; i < size; i++) { //convert multiple spaces to one space if(s[i] != ‘ ‘) { if(i == 0 || s[i-1] == ‘ ‘) { left = i; right = i; } else right ++; } else //if (s[i] == ‘ ‘) { if(i > 0 && s[i-1] != ‘ ‘) { //cout << "left\t" << left << endl; //cout << "right\t" << right<< endl; reverseWord(s, left, right); //move the part to writePos // it means memmove while(left <= right) { s[writePos++] = s[left++]; } s[writePos++] = ‘ ‘;//add space after the word } } } if( writePos > 0) //remove the latest space s.resize(writePos - 1); else s.resize(0);//the str only contains space } };
[LeetCode] Reverse Words in a String
标签:
原文地址:http://www.cnblogs.com/diegodu/p/4624932.html