本博客rss订阅地址: http://feed.cnblogs.com/blog/u/147990/rss

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 class Solution {
 2 public:
 3     void reverseWords(string &s) 
 4     {
 5         //从前往后扫描 
 6         string res, word;
 7         for(int i = s.size()-1; i >= 0;)
 8         {
 9             while(i >= 0 && s[i] == ' ')--i;//去掉空格
10             if(i < 0)break;
11             if(res.size() != 0)res.push_back(' ');
12             word.clear();
13             while(i >= 0 && s[i] != ' ')word.push_back(s[i--]);//word为找到的一个单词
14             for(int j = word.size()-1; j >= 0; --j)
15                 res.push_back(word[j]);
16         }
17         s = res;
18     }
19 };

 

【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3986615.html

posted @ 2014-09-22 19:59  tenos  阅读(1177)  评论(0编辑  收藏  举报

本博客rss订阅地址: http://feed.cnblogs.com/blog/u/147990/rss

公益页面-寻找遗失儿童