Leetcode Reverse Words in a String
来源:互联网 发布:青岛邮箱数据 编辑:程序博客网 时间:2024/06/06 03:37
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
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.
比较简单的一道题,先把整个字符串反转,然后对每一个单词进行反转,用i记录每个单词的开始位置,j记录每个单词的结束位置,同时i为负值来取出前、中、后多余的空格。定义两个变量i,j,不需要其他的变量
备注:对于reverse(),是左闭右开,即如果要反转“hi!”,那么是reverse(s.begin()+0,s.begin()+2+1).
class Solution {public: void reverseWords(string &s) { reverse(s.begin(),s.end()); for(int i=-1,j=0;j<s.length();j++){ if(s[j]==' '){ if(j==s.length()-1){s.erase(s.begin()+j);j-=2;i=-2;}//当最末尾为空格时,j需要减去2,因为外循环j+1 else if(i==-1){s.erase(s.begin()+j);j--;} else{ reverse(s.begin()+i,s.begin()+j); i=-1; } }else{ if(i==-1)i=j; if(j==s.length()-1&&i>=0)reverse(s.begin()+i,s.begin()+j+1);//避免最后一个单词两次反转 } } }};
0 0
- Leetcode - string - Reverse Words in a String
- Reverse words in a String leetcode
- [LeetCode]Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- Reverse Words in a String (LeetCode)
- LeetCode Reverse Words in a String Total
- LeetCode(151)Reverse Words in a String
- Reverse Words in a String -- LeetCode
- leetcode Reverse Words in a String
- LeetCode OJ:Reverse Words in a String
- LeetCode Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- [Leetcode] Reverse Words in a String
- Reverse Words in a String[LeetCode]
- LeetCode OJ :Reverse Words in a String
- Leetcode: Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- 静态数据管理类定义(单例模式)
- oracle 利用存储过程为表动态建立索引
- Swift 之 枚举
- MyEclipse8.5快捷键总结(持续更新)
- iosui学习中的课堂笔记 UISegmentedControl。UISlider。UIStepper。UISwitch。
- Leetcode Reverse Words in a String
- mahout算法源码分析之Itembased Collaborative Filtering(六)总结
- 随机数是骗人的,.Net、Java、C为我作证
- 分布式消息系统Kafka初步
- Java线程阻塞中断和LockSupport的常见问题
- js全角字符转为半角大写
- QFile 总结
- Java_DOM解析XML
- 读书笔记 --- 定位(iBeacon)