代码改变世界

[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".

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++来写的,稍微麻烦一点点。

 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     }