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.
思路:做两次旋转 和Rotate Array相似
void reverseChar(string& s,int begin,int end)
{
if(end < begin)
return ;
while(begin <= end)
{
swap(s[begin],s[end]);
begin++;
end--;
}
}
void reverseWords(string &s)
{
int len = s.length();
int i,j;
reverseChar(s,0,len-1);
for(i=0;i<len;)
{
for(j=i;j<len;j++)
if(s[j] == ' ')
break;
reverseChar(s,i,j-1);
i = j+1;
}
}