[Leetcode]Reverse Words in a String
2015-12-13 14:37
525 查看
Reverse Words in a String My Submissions Question
Total Accepted: 84277 Total Submissions: 546781 Difficulty: Medium
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.
click to show clarification.
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.
Subscribe to see which companies asked this question
Total Accepted: 84277 Total Submissions: 546781 Difficulty: Medium
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.
click to show clarification.
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.
Subscribe to see which companies asked this question
[code]class Solution { public: void reverseWords(string &s) { int len = s.size(); if(!len) return; int i = 0; while(s[i] == ' '){ ++ i; } s.erase(0,i); i = s.size() - 1; while(s[i] == ' '){ --i; } s.erase(i + 1); if(s.size() == 0) return; for(i = 0;i <= s.size() - 1;++ i){ int dis = 0; if(s[i] == ' ' && i + 1 <= s.size() - 1 && s[i + 1] == ' '){ dis = 1; while(i + dis + 1 <= s.size() - 1 && s[i + dis + 1] == ' '){ ++ dis; } s.erase(i + 1,dis); } } reverse(s.begin(),s.end()); for(int b = 0,e = 0;e <= s.size() - 1; ++ e){ if(s[e] == ' ' ){ reverse(s.begin() + b,s.begin() + e); b = e + 1; } else if(e == s.size() - 1){ reverse(s.begin() + b,s.end()); return; } } } };
相关文章推荐
- Java transient关键字
- iOS instancetype和id类型区别
- HDU 1498 50 years, 50 colors(最小点覆盖,坑称号)
- linux用户及权限管理-学习总结
- JSP实现计算器功能(网页版)
- JSP利用过滤器解决request中文乱码问题
- uva10167 (简单题)
- 自定义异常
- oracle临时表的使用(未完)
- EJB通过ANT提高EJB应用程序的开发效率、无状态发展本地接口bean、开发状态bean
- makefile模板
- 设置器(setter)和访问器(getter)的使用方法
- java中System类简介(转)
- Linux用户及权限管理
- Android LinearLayout,RelativeLayout 简要(随记四)
- kvm qemu libvirt区别
- java文件路径几种加载方式
- 程序设计、系统开发的一些资源
- 华为面试题:交换两个数组,使得数组的和的差最小
- zzulioj--1825-- 会长爱数学(模拟)