问题:翻转字符串中的单词顺序,如“hello world”变成“world hello”。要求使用常量空间。
c++代码如下:
void reverse(string &s, int start, int end){
int len=end+start;
int center=len/2;
for(int i=start;i<center;i++){
swap(s[i],s[len-1-i]);
}
}
void reverseWords(string &s) {
if(s=="")
return;
reverse(s,0,s.length());//全部反转
int start=0;
int end=start;
int len=s.length();
while(end<len){
while(start<len&&s[start]==' '){
start++;
}
end=start;
while(end<len&&s[end]!=' '){
end++;
}
reverse(s,start,end);//翻转每个单词,使之字母序恢复原状
start=end+1;
}
}