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

LeetCode:Reverse words in a String

时间:2015-06-05 22:36:57      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

Problem:

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

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

解法一:全局翻转 局部翻转 

     核心代码

 void reverseWords(string &str) {
    
    if(str.size()==0) return;
    
    auto beg = str.begin();
    auto end = str.end();
     
    reverse(beg,end);
     
    for(auto space = beg; space != end; ) 
    {
        space = std::find(beg,end,‘ ‘);
        reverse(beg,space);
        beg = space + 1;
    }

        
    }

 

别人家的代码

解法二:类似栈的思想  从后往前再翻转 每翻转一个则追加到结果字符串中

 

void reverseWords(string &s)
  {
    string rs;
    for (int i = s.length()-1; i >= 0; )
    {
      while (i >= 0 && s[i] == ‘ ‘) i--;
      if (i < 0) break;
      if (!rs.empty()) rs.push_back(‘ ‘);
      string t;
      while (i >= 0 && s[i] != ‘ ‘) t.push_back(s[i--]);
      reverse(t.begin(), t.end());
      rs.append(t);
    }
    s = rs;
  }

  

LeetCode:Reverse words in a String

标签:

原文地址:http://www.cnblogs.com/xiaoying1245970347/p/4555667.html

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