LeetCode-Reverse Words in a String
来源:互联网 发布:淘宝四大营销工具 编辑:程序博客网 时间:2024/06/05 19:50
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:
Solution:- 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.
Code:
class Solution {public: void reverseWords(string &s) { int length = s.size(); stack<string> stk; int start; bool word = false; for (int i = 0; i < length; ++i) if (s[i] == ' ' && word) { stk.push(s.substr(start, i-start)); word = false; } else if (s[i] != ' ' && !word) { word = true; start = i; } //attention if (word) stk.push(s.substr(start, length-start)); if (stk.empty()) { s = ""; return; } else { s = stk.top(); stk.pop(); while (!stk.empty()) { s += ' ' + stk.top(); stk.pop(); } return; } }};
0 0
- 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
- Selenium Webdriver java 积累
- mongoDB中Morphia接口封装
- 一致性 hash 算法( consistent hashing )
- hbase-zookeeper
- DS4000/DS5000添加新硬盘的步骤与注意事项
- LeetCode-Reverse Words in a String
- POJ2828 Buy Tickets
- resin安装使用
- Android四大基本组件及其生命周期
- poj 2914
- hbase 读写数据
- 音频标准AC97和IIS
- Sublime Text快捷键
- 匈牙利算法 大神讲解,秒懂