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

Leetcode:Reverse Words in a String

时间:2014-08-01 04:38:31      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   strong   io   for   art   

Description:

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

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

Clarification:

 

  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.

分析: 根据题目中的解释,基本就可以弄清这个题目的基本要求. 翻转字符串中的单词。 基本想法是用stack存所有的单词,然后重建字符串。

代码中的注释有分析,后面那个runtime error告诉我们几种极端测试检查是需要的!

然后注意那个常用trick,在处理一些边界条件时还是很有用的 

 1 class Solution {
 2 public:
 3     void reverseWords(string &s) {
 4         stack<string> rec;
 5         if(s.empty()) return;
 6         //这里有这个trick,在最后加一个标志字符,象征结束,免得还要在后面循环结束后,看是否还有
 7         //单词没有加入stack中,常用trick
 8         s = s+" ";
 9         string onec;
10         int startind = -1;
11         for(int i=0;i<s.size();i++)
12         {
13             if(s[i]==  && startind==-1) continue;
14             else if(s[i]== ){
15                 onec.assign(s.begin()+startind,s.begin()+i);
16                 rec.push(onec);
17                 onec.clear();
18                 startind = -1;
19                 continue;
20             }
21             else if (startind==-1) startind=i;
22             
23         }
24         s="";
25         //必须判断rec是否为空,否则会runtime error,因为后面的删除操作
26         if(rec.empty()) return;
27         while(!rec.empty())
28         {
29             s = s+ rec.top()+" ";
30             rec.pop();
31         }
32         s.erase(s.end()-1);
33         
34     }
35 };

 

Leetcode:Reverse Words in a String,布布扣,bubuko.com

Leetcode:Reverse Words in a String

标签:des   style   blog   color   strong   io   for   art   

原文地址:http://www.cnblogs.com/soyscut/p/3883773.html

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