zoukankan      html  css  js  c++  java
  • [LeetCode]Reverse Words in a String

    原题链接http://oj.leetcode.com/problems/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".

    click to show clarification.

    Clarification:
    • What constitutes a word?
      A sequence of non-space characters constitutes a word.
    • Could the input string contain leading or trailing spaces?
      Yes. However, your reversed string should not contain leading or trailing spaces.
    • How about multiple spaces between two words?
      Reduce them to a single space in the reversed string.

    题解:

      这道题真的很简单,尤其是用Java、C#这种对字符串操作的封装已经很强大的语言来写。我是用的C++来写的,稍微麻烦一点点。

     1 string Rtrim( string &str ){
     2         str.erase(std::find_if(str.rbegin(), str.rend(),std::not1(std::ptr_fun(::isspace))).base(),str.end());  
     3         return str;  
     4     }
     5     void reverseWords(string &s){
     6         vector<string> strs;
     7         int len = s.length();
     8         int start,end;
     9         bool flag = false;
    10         for(int i=0; i<len; i++){
    11             if(s[i]!=' ' && !flag){
    12                 start = i;
    13                 flag = true;
    14             }else if(s[i]==' ' && flag){
    15                 end = i;
    16                 flag = false;
    17                 strs.push_back(s.substr(start,end-start));
    18             }
    19         }
    20         if(flag){
    21             strs.push_back(s.substr(start,len-start));
    22         }
    23         s = "";
    24         while( !strs.empty() ){
    25             s+=strs.back();
    26             s+=" ";
    27             strs.pop_back();
    28         }
    29         s = Rtrim(s);
    30     }
  • 相关阅读:
    【14】算法 (哈希)
    【1】c++11 智能指针
    【13】算法 (平衡二叉树AVL、红黑色RBT、B+树、B-树详解)
    JavaScript 基础四
    JavaScript 基础三
    JavaScript 基础二
    遍历数组,对象和JSON
    创建对象的两种方式
    CSS3动画旋转——(图片360°旋转)
    产品运营和数据分析
  • 原文地址:https://www.cnblogs.com/codershell/p/3590409.html
Copyright © 2011-2022 走看看