Reverse Words in a String (LeetCode)
2014-03-08 12:32
621 查看
题目:
Given an input string, reverse the string word by word.
For example,
Given s = "
return "
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.
Given an input string, reverse the string word by word.
For example,
Given s = "
the sky is blue",
return "
blue is sky the".
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.
class Solution { public: void reverseWords(string &s) { vector<string> temp; string word = ""; string result = ""; if(s.empty()) return; for(string::size_type item = 0; item!=s.size();++item) { if(isspace(s[item])) { if(word!="") { temp.push_back(word); word = ""; } } else { word += s[item]; } } if(temp.empty()) { s=word; return; } if(word!="") { result += word + " "; } for(vector<string>::iterator iter = temp.end()-1; iter > temp.begin(); --iter) { result += *iter + " "; } result +=*temp.begin(); s = result; } };
相关文章推荐
- leetcode JAVA Reverse Words in a String 难度系数2-3?最新题151
- Leetcode -- Reverse Words in a String
- LeetCode Reverse Words in a String(反转字符串)
- Leetcode: Reverse Words in a String
- Reverse Words in a String leetcode java
- 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, python] Reverse Words in a String 反转字符串
- java中leetcode之Reverse Words in a String
- Leetcode-Reverse Words in a String
- LeetCode | Reverse Words in a String
- leetCode---Reverse Words in a String III
- [LeetCode] Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- LeetCode: Reverse Words in a String
- LeetCode151—Reverse Words in a String
- leetcode[151]:Reverse Words in a String
- [Leetcode][JAVA] Reverse Words in a String