151. Reverse Words in a String & 186.Reverse Words in a String II & 翻转单词顺序列
来源:互联网 发布:mac os x10.10raid 编辑:程序博客网 时间:2024/06/05 09:24
题目描述
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
解答
我们使用wi来表示第i个单词,用wi’表示翻转后的单词。注意,当将一个单词翻转两次后,可以得到原始的单词,即(wi’)’=wi。
输入的字符串是w1w2…wn。如果我们翻转整个字符串,我们将得到wn’…w2’w1’。然后我们将单词逐个翻转,就可以得到wn…w2w1。
class Solution {public: void reverseWords(string &s) { int length = s.length(); reverse(s.begin(),s.end()); int read = 0; int write = 0; while(read < length) { //skip leading white space and more than one white spaces between words if(s[read] == ' ') ++read; else { //record the start of a word int wordStart = read; //count the length of a word while(read < length && s[read] != ' ') ++read; //reverse current word reverse(s.begin() + wordStart,s.begin() + read); //copy current word to the appropriate position copy(s.begin() + wordStart,s.begin() + read,s.begin() + write); //move write to the end of current word write += read - wordStart; //add white space between words if(write < length) s[write] = ' '; //move write one step forward ++write; } } //s is not a empty string or string of white spaces if (write) { s = s.substr(0,write-1); } else s = ""; }};
0 0
- 151. Reverse Words in a String & 186.Reverse Words in a String II & 翻转单词顺序列
- 翻转单词顺序 Reverse Words in a String
- Reverse Words in a String 翻转单词顺序
- 151. Reverse Words in a String 翻转字符串中的单词
- Reverse Words in a String 翻转句子的单词
- Reverse Words in a String 翻转字符串
- Reverse Words in a String 反转单词顺序
- Reverse Words in a String II
- leetcode Reverse Words in a String II
- leetcode Reverse Words in a String II
- Reverse Words in a String II
- [Leetcode]Reverse Words in a String II
- Reverse Words in a String II
- *LeetCode-Reverse Words in a String II
- [LeetCode186]Reverse Words in a String II
- Reverse Words in a String II
- 【Leetcode】Reverse Words in a String II
- Reverse Words in a String II
- 使用Linux中sar命令性能定位分析的经验性步骤
- Linux Scp命令的使用
- 纯JS文本比较工具
- Android 手机蓝牙开发02
- java(15)--Servlet生成随机验证图片
- 151. Reverse Words in a String & 186.Reverse Words in a String II & 翻转单词顺序列
- 【代码笔记】iOS-翻书效果的实现
- C语言回调函数
- Linux服务器应急事件溯源报告
- Mysql 客户端连不上服务器,以及mongoVue连不上mongo问题解决
- C++模板学习
- ViewPager+Fragment+FragmentPagerAdapter,设置自定义刷新
- session 与 cookie介绍
- Android Studio 快捷键 高级篇