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

 

注意考虑有多个空格的情况就好了,选择的处理办法是在进行空格查找之前先整理字符串

 1 #include <string>
 2 #include <algorithm>
 3 using namespace std;
 4 class Solution {
 5 public:
 6     void reverseWords(string &s) {
 7         checkString(s);
 8         size_t found;
 9         string str;
10         found = s.find_last_of(" ");
11         while(found != string::npos){
12             str += s.substr(found+1) + " ";
13             s = s.substr(0,found);
14             found = s.find_last_of(" ");
15         }
16         str+=s;
17         s = str;
18     }
19     void checkString(string &s){
20         while(s[0] == ' ') s.erase(0,1);
21         if(s.size() == 0)    return;
22         while(s[s.size()-1] == ' ') s.erase(s.size()-1);
23         for(int i = 0; i < s.size()-1;i++){
24             if(s[i] == ' ' && s[i+1] == ' ') {
25                 s.erase(i--,1);
26             }
27         }
28         return ;
29     }
30 };

 

posted @ 2014-03-08 15:50  青轰的后花园  阅读(169)  评论(0编辑  收藏  举报