[Leetcode] 151. Reverse Words in a String 解题报告
来源:互联网 发布:淘宝网毛衣货源 编辑:程序博客网 时间:2024/06/05 09:00
题目:
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.
思路:
刷题刷久了,就忘了面试中关键的一个考察点,就是对一个题目有疑惑的时候,一定要记得和面试官讨论,进行clarification。上面写到的三点clarification都是非常重要的,直接关系到代码该怎么写。
其实算法的思路也算是比较明确的:1)每当检测出来一个单词时,对其进行翻转;2)当所有的单词被检测出来时,对整个字符串再进行一次翻转。由于原字符串中有可能存在多余的空格,所以我们在扫描过程中,需要在字符串内部进行复制,以将多余的空格给覆盖掉。具体见下面的代码片段。该思路的时间复杂度是O(n),空间复杂度是O(1)。
代码:
class Solution {public: void reverseWords(string &s) { int len = s.size(); int left = 0, right = 0, i = 0, flag = false; while(i < len) { while(s[i] == ' ') // trim the leading space i++; if(i == len) // already at the end break; if(flag) s[right++] = ' '; left = right; while(i < len && s[i] != ' ') s[right++] = s[i++]; reverse(s, left, right-1); flag = true; // flag is used to judge whether append " " } s.resize(right); reverse(s, 0, right - 1); }private: void reverse(string&s, int left, int right) { while(left < right) { char ch = s[right]; s[right--] = s[left]; s[left++] = ch; } }};
0 0
- [leetcode] 151. Reverse Words in a String 解题报告
- [Leetcode] 151. Reverse Words in a String 解题报告
- [leetcode]151. Reverse Words in a String@Java解题报告
- leetcode解题报告 Reverse Words in a String
- LeetCode 解题报告 Reverse Words in a String
- [LeetCode OJ] Reverse Words in a String 解题报告
- 【LeetCode】Reverse Words in a String 解题报告
- [leetcode] 186. Reverse Words in a String II 解题报告
- 【LeetCode】Reverse Words in a String III 解题报告
- [Leetcode] 186. Reverse Words in a String II 解题报告
- [Leetcode] 557. Reverse Words in a String III 解题报告
- LeetCode 151. Reverse Words in a String
- LeetCode 151. Reverse Words in a String
- [LeetCode]151.Reverse Words in a String
- [leetcode] 151.Reverse Words in a String
- Leetcode-151.Reverse Words in a String
- Leetcode 151. Reverse Words in a String
- [leetcode]151. Reverse Words in a String
- Ijkplayer Android介绍
- greendao3.2简单配置
- 51NOD 1605 棋盘问题 博弈
- jdk遇到设计模式之模板方法
- AndroidStudio关于jniLibs文件夹的个人理解
- [Leetcode] 151. Reverse Words in a String 解题报告
- 二阶段提交,三阶段提交,Paxos
- 复习
- Linux基础
- MVC5+Unity4.0注入依赖学习
- [bzoj2127] happiness 最小割
- 微信小程序开发—(十二)列表
- 大前端
- java poi上传excel保存数据库