码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode#151 Reverse Words in a String

时间:2015-01-30 10:30:11      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

原题地址

 

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

 

代码:

 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                 else
19                     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

标签:

原文地址:http://www.cnblogs.com/boring09/p/4261528.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!