LeetCode 题解(262) : Reverse Words in a String II
来源:互联网 发布:局内Windows无法访问 编辑:程序博客网 时间:2024/06/05 11:00
题目:
Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
Could you do it in-place without allocating extra space?
Related problem: Rotate Array
题解:先反转整个string,在反转每个单词。
C++版:
class Solution {public: void reverseWords(string &s) { reverse(s.begin(), s.end()); int i = 0; while(i < s.length()) { int j = i; while(j < s.length() && s[j] != ' ') j++; for(int k = i; k < i + (j - i) / 2; k++) { int t = s[k]; s[k] = s[i + j - 1 - k]; s[i + j - 1 - k] = t; } i = j + 1; } }};
Python版:
class Solution(object): def reverseWords(self, s): """ :type s: a list of 1 length strings (List[str]) :rtype: nothing """ s.reverse() i = 0 while i < len(s): j = i while j < len(s) and s[j] != " ": j += 1 for k in range(i, i + (j - i) / 2 ): t = s[k] s[k] = s[i + j - 1 - k] s[i + j - 1 - k] = t i = j + 1
0 0
- LeetCode 题解(262) : Reverse Words in a String II
- leetcode Reverse Words in a String II
- leetcode Reverse Words in a String II
- [Leetcode]Reverse Words in a String II
- *LeetCode-Reverse Words in a String II
- 【Leetcode】Reverse Words in a String II
- leetcode题解-151. Reverse Words in a String && 557. Reverse Words in a String III
- [LeetCode] Reverse Words in a String II(in-place 算法)
- LeetCode LeetCode 186 - Reverse Words in a String II
- 【leetcode题解】1 - Reverse Words in a String
- Reverse Words in a String ---leetcode 我的java题解
- LeetCode 题解(138): Reverse Words in a String
- LeetCode题解——Reverse Words in a String
- Leetcode NO.186 Reverse Words in a String II
- LeetCode - Reverse Words in a String I && II
- [leetcode] 186. Reverse Words in a String II 解题报告
- LeetCode 186.Reverse Words in a String II
- 【编程】【leetcode】186.Reverse Words in a String II
- UITextView自适应高度
- 开通自己的博客啦
- LeetCode 题解(261) : Game of Life
- mysql使用source导入,会自动断开并无法连接(编码问题)
- 编程习惯的总结
- LeetCode 题解(262) : Reverse Words in a String II
- 安卓高级计算器尝试第一阶段
- 【CS】高斯模糊GaussianBlur原理与实践
- 汉诺塔
- 对重构的理解
- Linux yum命令以及centOs安装jdk、tomcat、mysql
- oracle手注
- python rmq
- 【QT】QT4.8.6静态编译