Reverse Words in a String 有只扫一遍的inplace的做法吗?# JobHunting - 待字闺中
a*e
1 楼
终于有个不让我那么抓狂的题了,我的code如下,从后往前扫,两个指针,只扫一遍,
但不算inplace.
看到的其他inplace的好像要scan两遍,有只扫一遍的inplace的做法吗?
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
class Solution {
public:
void reverseWords(string &s) {
int len=s.size();
if (len==0) return;
int start=len-1,end=len-1;
while(s[end]==' '&&s[start]==' ')
{
end--;
start--;
}
string rs;
while(start>=0)
{
while(s[start]!=' '&&start>=0)
start--;
rs+=s.substr(start+1,end-start);
while(s[start]==' ')
start--;
if (start<0)
break;
rs+=' ';
end=start;
}
s=rs;
}
};
但不算inplace.
看到的其他inplace的好像要scan两遍,有只扫一遍的inplace的做法吗?
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
class Solution {
public:
void reverseWords(string &s) {
int len=s.size();
if (len==0) return;
int start=len-1,end=len-1;
while(s[end]==' '&&s[start]==' ')
{
end--;
start--;
}
string rs;
while(start>=0)
{
while(s[start]!=' '&&start>=0)
start--;
rs+=s.substr(start+1,end-start);
while(s[start]==' ')
start--;
if (start<0)
break;
rs+=' ';
end=start;
}
s=rs;
}
};