zoukankan      html  css  js  c++  java
  • 剑指offer之【翻转单词顺序列】

    题目:

      翻转单词顺序列

    链接:

      https://www.nowcoder.com/practice/3194a4f4cf814f63919d0790578d51f3?tpId=13&tqId=11197&rp=4&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

    题目描述:

      牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?

    思路:

      先对全部字符串进行翻转,然后对单个单词翻转

    代码:

      

     1 class Solution {
     2 public:
     3     string ReverseSentence(string str) {
     4         int len =0;
     5         while(str[len] != ''){
     6             ++len;
     7         }
     8         if(len <= 1){
     9             return str;
    10         }
    11         reverse(str,0,len-1);
    12         int start = 0;
    13         for(int i = 0; i<=len ; ++i){
    14             if(str[i]== ' '||str[i]== ''){
    15                 reverse(str,start,i-1);
    16                 start = i+1;
    17             }
    18         }
    19         return str;
    20     }
    21     void reverse(string &str, int l, int h){
    22         if(l>=h)
    23               return ;
    24         while(l<h){
    25             swap(str[l++],str[h--]);
    26         }
    27     }
    28 };
  • 相关阅读:
    扩展欧几里得(exgcd)与同余详解
    卡常模板
    文艺平衡树(区间翻转)
    Motto
    PKUWC2019划水记
    【模板】Splay(洛谷P3391)
    【PKUSC2018】最大前缀和
    【PKUWC2018】随机算法
    【PKUWC2018】Slay the Spire
    【PKUWC2018】Minimax
  • 原文地址:https://www.cnblogs.com/wangshujing/p/6946933.html
Copyright © 2011-2022 走看看