首页 > 其他 > 详细

[leetCode]Reverse Words in a String

时间:2014-03-08 18:19:34      阅读:531      评论:0      收藏:0      [点我收藏+]

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

 

注意考虑有多个空格的情况就好了,选择的处理办法是在进行空格查找之前先整理字符串

bubuko.com,布布扣
 1 #include <string>
 2 #include <algorithm>
 3 using namespace std;
 4 class Solution {
 5 public:
 6     void reverseWords(string &s) {
 7         checkString(s);
 8         size_t found;
 9         string str;
10         found = s.find_last_of(" ");
11         while(found != string::npos){
12             str += s.substr(found+1) + " ";
13             s = s.substr(0,found);
14             found = s.find_last_of(" ");
15         }
16         str+=s;
17         s = str;
18     }
19     void checkString(string &s){
20         while(s[0] ==  ) s.erase(0,1);
21         if(s.size() == 0)    return;
22         while(s[s.size()-1] ==  ) s.erase(s.size()-1);
23         for(int i = 0; i < s.size()-1;i++){
24             if(s[i] ==   && s[i+1] ==  ) {
25                 s.erase(i--,1);
26             }
27         }
28         return ;
29     }
30 };
bubuko.com,布布扣

[leetCode]Reverse Words in a String,布布扣,bubuko.com

[leetCode]Reverse Words in a String

原文:http://www.cnblogs.com/marylins/p/3588056.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!