您的位置:首页 > 其它

[LeetCode] Reverse Words in a String

2015-07-06 17:36 232 查看
Givenaninputstring,reversethestringwordbyword.Forexample,
Givens="
theskyisblue
",
return"
blueisskythe
".Update(2015-02-12):
ForCprogrammers:Trytosolveitin-placeinO(1)space.clicktoshowclarification.Clarification:Whatconstitutesaword?
Asequenceofnon-spacecharactersconstitutesaword.Couldtheinputstringcontainleadingortrailingspaces?
Yes.However,yourreversedstringshouldnotcontainleadingortrailingspaces.Howaboutmultiplespacesbetweentwowords?
Reducethemtoasinglespaceinthereversedstring.HideTagsString分析:
如果单词之间遇到多个空格,只能返回一个,而且首尾不能有单词,并且对C语言程序员要求空间复杂度为O(1),所以我们只能对原字符串s之间做修改,而不能声明新的字符串。第一步:反正整个字符串
第二部:反正单个word
第三部:将翻转好的word放到合适的位置,这里合适的位置是指前面的不包含space的位置。
writePos标记合适的位置,也就是将要写入的位置。

第四部:改变字符串大小


另外,我们在最后压入了一个space,是为了最后的word可以统一处理。

注意这段code,是为了处理整个字符串都是space的情况。
if(writePos>0)//removethelatestspace
s.resize(writePos-1);
else
s.resize(0);//thestronlycontainsspace
总之,此题是一道好体,题小乾坤大,很多细节需要处理。ACcode:
classSolution{
private:
voidreverseWord(string&s,intleft,intright)
{
chartmp;
while(left<right)
{
tmp=s[left];
s[left]=s[right];
s[right]=tmp;
left++;
right--;
}
}
public:
voidreverseWords(string&s){
if(s.size()==0)
return;//reverseallwords
reverseWord(s,0,s.size()-1);s.push_back('');//inordertohandlerthelatestpart
intsize=s.size();intwritePos=0;//positionwhichwillbewrittenintleft=0,right=0;
for(inti=0;i<size;i++)
{
//convertmultiplespacestoonespace
if(s[i]!='')
{
if(i==0||s[i-1]=='')
{
left=i;
right=i;
}
else
right++;
}
else//if(s[i]=='')
{
if(i>0&&s[i-1]!='')
{
//cout<<"left\t"<<left<<endl;
//cout<<"right\t"<<right<<endl;
reverseWord(s,left,right);//movetheparttowritePos
//itmeansmemmove
while(left<=right)
{
s[writePos++]=s[left++];
}
s[writePos++]='';//addspaceaftertheword
}
}
}if(writePos>0)//removethelatestspace
s.resize(writePos-1);
else
s.resize(0);//thestronlycontainsspace
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: