[LeetCode]Reverse Words in a String
来源:互联网 发布:笛子模仿软件 编辑:程序博客网 时间:2024/05/15 01:22
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.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.
这道题要求将一个字符串中的单词顺序反转,单词内部不反转,同时将单词间的多个空格合并成一个,头尾的空格删除。
思路:
1. 将整个字符串按照字母整个进行反转
2. 单词内进行反转,设置first和last分别表示单词的结束和开始,N个空格的第一个的前一个位置是单词的结尾,N个空格的最后一个的下一个是单词的开始。同时删去多余的空格。
3. 不额外使用存储空间。
下面贴上代码:
class Solution {public: void reverseWords(string &s) { reverse(s.begin(), s.end()); int first=0; int last=0; int i = 0; while (first != s.length()){ while (first != s.length() && s[first] == ' ') first++; last = first; while (last != s.length() && s[last] != ' ') last++; if (i != 0 && first <= last - 1) s[i++] = ' '; for (int j = last - 1; first < j; first++, j--){ swap(s[j], s[first]); s[i++] = s[first]; } while (first < last){ s[i++] = s[first++]; } } s.resize(i); }};
- 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
- Linux目录解释
- Twig中文说明手册
- 玩转OpenWrt
- const对链接性的影响&类的常量&java调用shell命令&codeblocks的配置文档路径
- Java执行过程详解 -- JVM生命周期
- [LeetCode]Reverse Words in a String
- Struts2+Tiles2框架整合
- Android开发——Android开发入门
- vba日期和时间函数汇总和代码
- MarkDown教程
- Oracle的get命令
- linux的mount(挂载)命令详解
- BGP选路详解
- Myeclipse 中的自动输入问题