[LeetCode]Reverse Words in a String
2014-03-09 19:02 庸男勿扰 阅读(308) 评论(0) 编辑 收藏 举报原题链接:http://oj.leetcode.com/problems/reverse-words-in-a-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.
题解:
这道题真的很简单,尤其是用Java、C#这种对字符串操作的封装已经很强大的语言来写。我是用的C++来写的,稍微麻烦一点点。
1 string Rtrim( string &str ){ 2 str.erase(std::find_if(str.rbegin(), str.rend(),std::not1(std::ptr_fun(::isspace))).base(),str.end()); 3 return str; 4 } 5 void reverseWords(string &s){ 6 vector<string> strs; 7 int len = s.length(); 8 int start,end; 9 bool flag = false; 10 for(int i=0; i<len; i++){ 11 if(s[i]!=' ' && !flag){ 12 start = i; 13 flag = true; 14 }else if(s[i]==' ' && flag){ 15 end = i; 16 flag = false; 17 strs.push_back(s.substr(start,end-start)); 18 } 19 } 20 if(flag){ 21 strs.push_back(s.substr(start,len-start)); 22 } 23 s = ""; 24 while( !strs.empty() ){ 25 s+=strs.back(); 26 s+=" "; 27 strs.pop_back(); 28 } 29 s = Rtrim(s); 30 }
作者:庸男勿扰
出处:http://www.cnblogs.com/codershell
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
如果您觉得对您有帮助,不要忘了推荐一下哦~
出处:http://www.cnblogs.com/codershell
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
如果您觉得对您有帮助,不要忘了推荐一下哦~