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

reverse the string word by word

时间:2014-07-16 19:29:54      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   2014   

题目:Given an input string, reverse the string word by word.

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

要求:

1)首尾有空格的时候,反转后的string要将空格去掉

2)当string有多个连续空格的时候,只保留一个空格、

bubuko.com,布布扣

 

代码分析:

对多余空格剔除:

bubuko.com,布布扣

思路分析:

1)从原始s 的最末尾开始扫描,如果遇到空格,用while剔除掉。

2)接下来从第一个非空格读取,存入一个temp的string中,然后调用string::reverse() 反转,并string::append()到ss中。

3)重复1、2步,但是有几个情况需要注意:

    a.我们从末尾扫描,当扫描到空格,后,由于ss为空,所以不会push.back(‘ ‘)到ss中。

    b.中间有空格的,我们剔除完空格后就需要再增加一个‘ ‘,

    c.最开始的空格怎么处理呢?我们用到

  1.  if (string_index < 0)     
  2.        break;
也就是剔除了空格后,如果此时的index已经是最开头了,那么我们就退出循环。
 
 
 
 
 





reverse the string word by word,布布扣,bubuko.com

reverse the string word by word

标签:style   blog   http   color   os   2014   

原文地址:http://www.cnblogs.com/menghuizuotian/p/3841270.html

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