首页 > 代码库 > Leetcode:Reverse Words in a String

Leetcode:Reverse Words in a String

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 };