LeetCode | Reverse Words in a String(字符串中的单词序反转)
来源:互联网 发布:ios 存储数组 编辑:程序博客网 时间:2024/05/17 03:24
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
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.
题目解析:
题目中要删除多余的空格,有一种比较简单的方法,先将s字符串赋给一个临时字符串tmp,将头尾空格略去,两个字间的空格只复制一次。然后对tmp进行常规操作。这样需要两遍遍历。
也可以临时设一个结果字符串,和一个临时的字串。一点一点处理
class Solution {public: void reverseWords(string &s) { string tmp; for(int i = s.size()-1;i >= 0;i--){ while(i >= 0 && s[i] == ' ') i--; if(i<0) break; if(!tmp.empty()) tmp.push_back(' '); string word; while(i>=0 && s[i]!=' ') word.push_back(s[i--]); reverse(word.begin(),word.end()); tmp.append(word); } s = tmp; }};
0 0
- LeetCode | Reverse Words in a String(字符串中的单词序反转)
- LeetCode之186_Reverse Words in a String 字符串词序反转算法
- LeetCode 557 Reverse Words in a String III(反转字符串中的单词3)
- LeetCode Reverse Words in a String(反转字符串)
- LeetCode Reverse Words in a String(反转字符串)
- 字符串反转 reverse-words-in-a-string @LeetCode
- [leetcode, python] Reverse Words in a String 反转字符串
- leetcode Reverse Words in a String III 反转字符串中的单词
- 【LeetCode-面试算法经典-Java实现】【151-Reverse Words in a String(反转字符串中的单词)】
- LeetCode 151. Reverse Words in a String(反转单词)
- 字符串算法——反转字符串单词表(Reverse Words in a String)
- [LeetCode]Reverse Words in a String-反转单词
- [Leetcode] reverse words in a string 反转单词
- Reverse Words in a String 字符串中单词反转
- [LeetCode]557. Reverse Words in a String III(反转字符串 III)
- LeetCode刷题:Reverse Words in a String(翻转字符串中的单词)
- Leetcod:557.Reverse Words in a String III 反转字符串中的每个单词。
- Reverse Words in a String (LeetCode)
- MATLAB学习心得~
- 定制导航栏和状态栏
- hadoop+hive-完全分布式环境搭建
- codeforces 458B
- 【爱上Java8】Java 8 不在需要ORM了
- LeetCode | Reverse Words in a String(字符串中的单词序反转)
- PyQt4在TextEdit控件中创建右键菜单
- Leetcode【15】:3Sum
- FASDVZXCVZXCV
- 二极管、三极管、场效应管的原理及特性
- 函数包装器,函数私有类处理
- C语言 select函数使用
- java 8 使用Lambdas, Paths and Files
- 函数模板,函数模板重载,可变参数模板,函数模板覆盖,通过引用交换数据