您的位置:首页 > 其它

LeetCode : Reverse Words in a String

2014-05-21 17:48 211 查看
Given an input string, reverse the string word by word.

For example,

Given s = "
the sky is blue
",

return "
blue is sky the
".

click to show clarification.
 

void reverseWords(string &s) {
int length=s.size();

if(length==0) return ;
int pre=0;
int post=length-1;
while(pre<post){
swap(s[pre],s[post]);
++pre;
--post;
}
int start=0;
int end=0;
while(end<length){
while(end<length&&s[end]!=' '){
end++;
}
pre=start;
post=end-1;
while(pre<post){
//swap(s[pre],s[post]);
char ch=s[pre];
s[pre]=s[post];
s[post]=ch;
++pre;
--post;
}
while(end<length&&s[end]==' '){
end++;
}
start=end;
}
int len=s.size();
int low=0;
int fast=0;

while(fast<len){
if(s[fast]!=' '||((fast+1<len)&&s[fast]==' '&&s[fast+1]!=' '&&low!=0)){
low++;
}
fast++;
s[low]=s[fast];
}
s.resize(low,'\0');
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: