[Lintcode]Reverse Words in a String

来源:互联网 发布:淘宝女装店铺起名 编辑:程序博客网 时间:2024/05/18 01:40

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.
class Solution {public:    /**     * @param s : A string     * @return : A string     */    string reverseWords(string s) {        // write your code here        string res="";        int len=s.size();        int start=0;        while(start<len) {            while(s[start]==' ')                 start++;            if(start>=len) break; //注意后置0            int index=-1;            index=s.find(" ",start);            string tmp;            if(index==-1) index=len;            tmp=s.substr(start,index-start);            if(res.size()==0) res=tmp;            else res=tmp+" "+res;            start=index+1;        }        return res;    }};


0 0