设为首页 加入收藏

TOP

Leetcode - Reverse Words
2015-07-24 07:26:41 来源: 作者: 【 】 浏览:147
Tags:Leetcode Reverse Words

比起POJ弱爆了一题,从后往前扫描一遍,O(n)时间,只要注意各种极端情况即可,不明白通过率为什么只有13%。


#include
  
   
#include
   
     using namespace std; class Solution { public: void reverseWords(string &s) { char* cstr = new char[s.size()+1]; int cc = 0; int revstrC = s.size() - 1; while (revstrC >= 0) { while (revstrC>=0 && s.at(revstrC) == ' ') { revstrC--; } if (revstrC >= 0)//find the end of a word { int end = revstrC; while (revstrC >= 0 && s.at(revstrC) != ' ') revstrC--; s.copy(cstr+cc, end-revstrC, revstrC+1); cc = cc + end - revstrC; cstr[cc] = ' '; cc++; } } cstr[cc-1] = '\0'; s.assign(cstr); } }; int main() { Solution sol; string str = " Hello fwe asg wf vergv "; sol.reverseWords(str); cout << str << endl; }
   
  


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇HDU2577dp基础 下一篇POJ 1150 The Last Non-zero Digi..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: