【leetcode】151. Reverse Words in a String
来源:互联网 发布:淘宝朋友代付怎么查看 编辑:程序博客网 时间:2024/06/08 09:49
题目:
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.
c++代码:
class Solution {public: void reverseOneWord(string &s, int start, int end){ while(start<end){ swap(s[start++],s[end--]); } } void reverseWords(string &s) { int i=0; //快 int j=0; //慢 int len=s.size(); int word_count=0; while(i<len){ while(i<len && s[i]== ' '){ //找到下一个不为空的字符串 i++; }//while if(i>=len){ break; } if(word_count>0){ //如果不是第一个单词,那么每个单词前都需要加一个空格 s[j++]=' '; } int start=j; for(;i<len && s[i]!=' ';i++,j++){ //从i开始的单词,移动到从j开始 s[j]=s[i]; } reverseOneWord(s, start, j-1); //翻转当前单词 word_count++; }//while s.resize(j); //去掉最后一个单词后面的空字符串 reverseOneWord(s, 0, j-1); //翻转整个单词 }};
0 0
- 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
- 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
- [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
- 用PHP实现同时产生多个不同的随机数
- SSL 1045——采药
- std::vector : 用法与技巧
- Linux性能评测工具之一:gprof篇
- 递归1
- 【leetcode】151. Reverse Words in a String
- 25、VS2012中给C++的main函数传递参数
- 395. Longest Substring with At Least K Repeating Characters
- docker -- Namespace资源隔离
- 从“用户访问网页”实例看互联网协议的运作
- hiho一下 第一百三十四周 #1468 : 2-SAT·hihoCoder新春晚会 【2-SAT 之 枚举--搜索】
- UVA 11882 Biggest Number (dfs搜索+bfs 剪枝)
- #cs231n#相关资源
- 析构函数