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

Leetcode#151 Reverse Words in a String

原题地址

 

将单词按空格分词,然后倒序拼接即可

 

代码:

 1 void reverseWords(string &s) { 2         vector<string> words; 3          4         int start = -1; 5         int len = 0; 6          7         for (int i = 0; i < s.length(); i++) { 8             if (s[i] ==  ) { 9                 if (len > 0)10                     words.push_back(s.substr(start, len));11                 len = 0;12             }13             else {14                 if (len == 0) {15                     start = i;16                     len = 1;17                 }18                 else19                     len++;20             }21         }22         if (len > 0)23             words.push_back(s.substr(start, len));24         25         string res;26         if (words.size() > 0) {27             for (int i = words.size() - 1; i > 0; i--)28                 res += words[i] + " ";29             res += words[0];30         }31         32         s = res;33 }

 

Leetcode#151 Reverse Words in a String