leetcode6 Reverse Words in a String 单词取反

   Reverse Words in a String  单词取反

    whowhoha@outlook.com

Question:

Given an input string s, reverse the string word by word.

For example, given s = "the sky is blue", return "blue is sky the".

void reverseWords(string &s) {

        vector <string>des;

        if(s.empty())

                 return;

        int len = s.size();

        for(int i = 0; i < len; i++){

                 if(s[i] == ' ')

                         continue;

                 string word;

                 while(i < len && s[i] != ' '){

                         word += s[i];

                         i++;

                 }

                 des.push_back(word);

        }

        reverse(des.begin(), des.end());

        if(des.empty())

                 s = "";

        else {

                 s.clear();

                 int j ;

                 for(j = 0; j < des.size() -1; j++){

                         s += des[j];

                         s += ' ';

                 }

                 s += des[j];   

        }

}

posted @ 2016-08-06 09:03  whowhoha  阅读(174)  评论(0编辑  收藏  举报