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

LeetCode: Reverse Words in a String

时间:2014-07-27 23:33:19      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   strong   io   for   代码   

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

题目地址:https://oj.leetcode.com/problems/reverse-words-in-a-string/

算法:先把字符串分成一个一个word放在vector里面,然后在按逆序存入原来的字符串里。代码:

 

 1 class Solution {
 2 public:
 3     void reverseWords(string &s) {
 4         vector<string> words = split(s);
 5         s.clear();
 6         vector<string>::reverse_iterator iter = words.rbegin();
 7         if(iter != words.rend()){
 8             s += *iter;
 9             ++iter;
10         }
11         for(; iter != words.rend(); ++iter){
12             s += " ";
13             s += *iter;
14         }
15     }
16     vector<string> split(const string &s){
17         string t;
18         vector<string> words;
19         string::const_iterator p = s.begin();
20         while(p != s.end()){
21             while(p != s.end() && isspace(*p)){
22                 ++p;
23             }
24             while(p != s.end() && !isspace(*p)){
25                 t.push_back(*p);
26                 ++p;
27             }
28             if(!t.empty()){
29                 words.push_back(t);
30                 t.clear();
31             }
32         }
33         return words;
34     }
35 };

 

LeetCode: Reverse Words in a String,布布扣,bubuko.com

LeetCode: Reverse Words in a String

标签:style   blog   http   color   strong   io   for   代码   

原文地址:http://www.cnblogs.com/boostable/p/leetcode_reverse_words_in_a_string.html

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