码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode] Reverse Words in a String

时间:2015-03-05 14:37:43      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

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

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
 
 1 class Solution
 2 {
 3 public:
 4   void reverseWords(string &s)
 5   {
 6     string temp = "", s1 = "";
 7     for(int i=s.size()-1; i>=0;)
 8     {
 9       if(s[i] ==   || i == 0) 
10       {
11         if(i == 0 && s.size()>0 && s[i+1] !=   && s[i] !=  )
12           temp = s[i--] + temp;
13         else if(i == 0 && s[i] !=  )
14           temp = s[i--];
15 
16         while(s[i] ==  ) i--;
17 
18         if(s1 == "")
19           s1 = temp;
20         else
21           s1 += " " + temp;
22 
23         temp = ""; 
24       }
25       else if(s[i] !=  )
26         temp = s[i--] + temp;
27     }
28 
29     s = s1;
30   }
31 };

 

[leetcode] Reverse Words in a String

标签:

原文地址:http://www.cnblogs.com/lxd2502/p/4315656.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!