Leetcode Reverse Words in a String

OpenSoucre發表於2014-06-18

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

 

 

相關文章