首页 > 其他 > 详细

Leetcode Reverse Words in a String

时间:2014-06-28 22:48:23      阅读:388      评论: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".


此题要注意的几个情况是:

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

 

 

Leetcode Reverse Words in a String,布布扣,bubuko.com

Leetcode Reverse Words in a String

原文:http://www.cnblogs.com/xiongqiangcs/p/3794233.html

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