Leetcode -- Reverse Words in a String
2015-10-28 23:03
260 查看
Given an input string, reverse the string word by word.
For example,
Given s = "
return "
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
Clarification:
What constitutes a word?
A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
分析:
先去除多余的空格,再做两次reverse。
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.
Clarification:
What constitutes a word?
A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
分析:
先去除多余的空格,再做两次reverse。
class Solution { public: void reverseWords(string &s) { for(int i=0;i<s.size();) { if(s[i]==' '&&(i==0||i==s.size()-1||s[i+1]==' ')) s.erase(i,1); else i++; } int n=s.size(); if(n==0) return; reverse(s.begin(),s.end()); for(int i=0;i<s.size();) { int j=i+1; while(j<n&&s[j]!=' ') j++; reverse(next(s.begin(),i),next(s.begin(),j)); i=j+1; } } };
相关文章推荐
- LightOJ - 1057 Collecting Gold(状压DP)
- 负margin的经典利用之用绝对定位来居中
- postgresql function 返回 select
- Subsets II
- 控制器的View的创建
- Unity如何将包缩小到极致
- alibaba fastjson joda time 解析器
- HTTP报文内的HTTP信息之编码提升传输速率
- java 通过userAgent获取访问者的操作系统与浏览器
- LightOJ - 1051 Good or Bad(扫描)
- ctive-c中 isEqual ,isEqualToString , == 三者的区别
- Segmentation fault到底是何方妖孽
- 数据结构练习2——括号匹配
- Android自定义相机拍照、图片裁剪的实现
- 为什么博客园安卓端无法登陆,真服了
- C++连接mysql数据库的两种方法
- ExtJs关于Ext.extend()的说明
- 第二百零九天 how can I 坚持
- Java中增强型for循环的样例和解释
- URL传递中文参数乱码问题