您的位置:首页 > 其它

151. Reverse Words in a String

2016-03-18 22:31 477 查看
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.

click to show clarification.

Subscribe to see which companies asked this question

class Solution {

public:

void reverseWords(string &s) {

reverse(s.begin(),s.end());

int before=0;

//int end=0;

for(int i=0;i<s.size();i++){

if(s[i]==' '){

while(s[i+1]==' '){

s.erase(s.begin()+i+1);

}

reverse(s.begin()+before,s.begin()+i);

before=i+1;

//end=i;

}

}

reverse(s.begin()+before,s.end());

int j=0;

while(s[j]==' '){

s.erase(s.begin()+j);

//j++;

}

int end=s.size();

while(s[end-1]==' '){

s.erase(s.begin()+end-1);

}

if(s[end-1]==' '){

s.erase(s.begin()+end);

}

}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: