[LeetCode] Reverse Words in a String
2015-07-06 17:36
232 查看
Givenaninputstring,reversethestringwordbyword.Forexample,
Givens="
return"
ForCprogrammers:Trytosolveitin-placeinO(1)space.clicktoshowclarification.Clarification:Whatconstitutesaword?
Asequenceofnon-spacecharactersconstitutesaword.Couldtheinputstringcontainleadingortrailingspaces?
Yes.However,yourreversedstringshouldnotcontainleadingortrailingspaces.Howaboutmultiplespacesbetweentwowords?
Reducethemtoasinglespaceinthereversedstring.HideTagsString分析:
如果单词之间遇到多个空格,只能返回一个,而且首尾不能有单词,并且对C语言程序员要求空间复杂度为O(1),所以我们只能对原字符串s之间做修改,而不能声明新的字符串。第一步:反正整个字符串
第二部:反正单个word
第三部:将翻转好的word放到合适的位置,这里合适的位置是指前面的不包含space的位置。
第四部:改变字符串大小
注意这段code,是为了处理整个字符串都是space的情况。
Givens="
theskyisblue",
return"
blueisskythe".Update(2015-02-12):
ForCprogrammers:Trytosolveitin-placeinO(1)space.
Asequenceofnon-spacecharactersconstitutesaword.Couldtheinputstringcontainleadingortrailingspaces?
Yes.However,yourreversedstringshouldnotcontainleadingortrailingspaces.Howaboutmultiplespacesbetweentwowords?
Reducethemtoasinglespaceinthereversedstring.HideTags
如果单词之间遇到多个空格,只能返回一个,而且首尾不能有单词,并且对C语言程序员要求空间复杂度为O(1),所以我们只能对原字符串s之间做修改,而不能声明新的字符串。第一步:反正整个字符串
第二部:反正单个word
第三部:将翻转好的word放到合适的位置,这里合适的位置是指前面的不包含space的位置。
writePos标记合适的位置,也就是将要写入的位置。
第四部:改变字符串大小
另外,我们在最后压入了一个space,是为了最后的word可以统一处理。
注意这段code,是为了处理整个字符串都是space的情况。
if(writePos>0)//removethelatestspace总之,此题是一道好体,题小乾坤大,很多细节需要处理。ACcode:
s.resize(writePos-1);
else
s.resize(0);//thestronlycontainsspace
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
}
};
相关文章推荐
- Dota2技能系统设计分析
- Windows知识点记录
- Call WebService - Request format is unrecognized for URL unexpectedly ending
- hdu 1874 畅通工程续(两点最短路径,spfa&&floyd)
- HDU 5073 Galaxy(贪心)
- 直接从链接往jsp页面传值的问题
- qt5输入的一些细节
- Linux下查看文件内容的命令 (
- javascript内置函数
- 五步搞定Android开发环境部署——非常详细的Android开发环境搭建教程
- iOS开发-UINavigationBar透明设置
- HTML5 本地裁剪图片
- java decode
- java.util.concurrent
- Oracle之分页查询
- JSON解析 ---- NSJSONSerialization介绍
- Linux Socket编程注意事项
- Font Awesome使用简介
- zabbix监控tcp连接数
- Android ViewPager的使用以及定时切换实现