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


此题要注意的几个情况是:

(1)输入字符串可能含有前缀0和后缀0

(2)字符串中每个单词之间可能含有多个空格

(3)字符串是空串

(3)字符串只有一个单词

此题主要是根据空格分隔单词,然后将分隔后单词的顺序逆转一下即可

void reverseWords(string &s){
   string buf;
   stringstream ss(s);
   vector<string> word;
   while(ss >> buf) word.push_back(buf);
   if(word.size() == 0) s="";
   else{
       s="";
       int n = word.size();
        for(int i = n  -1; i >=0; -- i){
            if(i!=n-1) s+=" ";
            s+=word[i];
        }
   }
}
 
原文地址:https://www.cnblogs.com/xiongqiangcs/p/3794233.html