class Solution { public: void reverseWords(string &s) { int len = s.length(); reverse(s.begin(), s.end()); int wpos = 0; for (int p=0, q=0; p < len; p = q) { while ((p<len) && (s[p] == ' ')) p++; q = p; while ((q<len) && (s[q] != ' ')) q++; reverse(s.begin() + p, s.begin() + q); if (wpos != 0 && p < q) s[wpos++] = ' '; for (int i=p; i<q; i++) { s[wpos++] = s[i]; } } if (wpos != len) s = s.substr(0, wpos); } };
还要处理多余空格
第二轮:
艹怎么感觉代码写的反而多了
void reverse(char* s, int start, int end) { int p = start; int q = end-1; while (p < q) { char t = s[p]; s[p] = s[q]; s[q] = t; p++, q--; } } void reverseWords(char *s) { if (s == NULL) { return; } int wpos = 0; int rpos = 0; int inWord = 0; int last = 0; char ch = 0; while ((ch = s[rpos]) != ' ') { if (inWord) { if (ch == ' ') { // one word end, reverse it reverse(s, last, wpos); inWord = 0; } else { // word continue s[wpos++] = ch; } } else { if (ch == ' ') { // skip space } else { // one word begin inWord = 1; if (wpos>0) { s[wpos++] = ' '; // space between last word } last = wpos; // mark where word begin s[wpos++] = s[rpos]; } } rpos++; } s[wpos] = ' '; if (wpos > 0 && s[rpos-1] != ' ') { // reverse last word reverse(s, last, wpos); } // reverse whole string reverse(s, 0, wpos); }