[LeetCode]Reverse Words in a String
2014-03-09 19:02
555 查看
原题链接:http://oj.leetcode.com/problems/reverse-words-in-a-string/
题目描述:
Given an input string, reverse the string word by word.
For example,
Given s = "
return "
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.
题解:
这道题真的很简单,尤其是用Java、C#这种对字符串操作的封装已经很强大的语言来写。我是用的C++来写的,稍微麻烦一点点。
题目描述:
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.
题解:
这道题真的很简单,尤其是用Java、C#这种对字符串操作的封装已经很强大的语言来写。我是用的C++来写的,稍微麻烦一点点。
string Rtrim( string &str ){ str.erase(std::find_if(str.rbegin(), str.rend(),std::not1(std::ptr_fun(::isspace))).base(),str.end()); return str; } void reverseWords(string &s){ vector<string> strs; int len = s.length(); int start,end; bool flag = false; for(int i=0; i<len; i++){ if(s[i]!=' ' && !flag){ start = i; flag = true; }else if(s[i]==' ' && flag){ end = i; flag = false; strs.push_back(s.substr(start,end-start)); } } if(flag){ strs.push_back(s.substr(start,len-start)); } s = ""; while( !strs.empty() ){ s+=strs.back(); s+=" "; strs.pop_back(); } s = Rtrim(s); }
相关文章推荐
- 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
- 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