思路: 本题考查的目的并不是使用字符串的函数。方法是两次reverse,先对每个单词先做一次翻转,然后对整个字符串做一次翻转。
需要注意的是去除extra space,并且对全space字符串、以及最后一个单词要做特殊处理。
class Solution { public: void reverseWords(string &s) { int start = 0; int end=-1; int i = 0; int cur = 0; // point to the string with extra space deleted //ignore space at the beginning while(i < s.length() && s[i]==' '){ i++; } for(;i<s.length();i++){ if(s[i]==' ' && i+1 < s.length() && s[i+1] ==' ') continue; //ignore extra space between words if(s[i]==' ' && i+1 == s.length()) break; //ignore final space s[cur++] = s[i]; if(s[i]==' '){ end = cur-2; //end case1: the letter before space reverse(s, start, end); start = cur; } } end = cur-1; //end case2: the last not space letter!!! if(end == -1) s = ""; //special case: null string!!! if(s[i-1] != ' '){ //reverse the last word!!! reverse(s,start,end); } cout << "end=" << end << endl; s = s.substr(0, end+1); reverse(s,0,end); } void reverse(string &s, int start, int end){ int l = start; int r = end; char tmp; while(l<r){ tmp = s[l]; s[l]=s[r]; s[r]=tmp; l++; r--; } } };