zoukankan      html  css  js  c++  java
  • leetCode题解 Reverse Words in a String III

    1、题目描述

         Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.  

          Example 1:

              Input: "Let's take LeetCode contest"

              Output: "s'teL ekat edoCteeL tsetnoc"

            Note: In the string, each word is separated by single space and there will not be any extra space in the string.

    输入一个string 结构的句子,单词之间使用一个空格隔开(' '),将句子中的每个单词单独反转。保持反转之后每个单词在句子中的位置。

    2、问题分析

        每个单词之间使用空格隔开,遍历一次string ,寻找空格,然后反转该空格之前的单词,一直到结尾。

    3、代码

     1  string reverseWords(string s) {
     2         
     3         s = s+' '; // 给string 后面添加一个空格,用于反转最后一个单词。
     4         auto b = s.begin();  // C++11 特性,迭代器
     5         auto e = s.end();
     6         
     7         auto p =s.begin();  // 这个迭代器在每次反转之后更新,指向最近一个没有被反转的单词
     8         for(b = s.begin(); b != e; ++b)
     9         {
    10             if(*b == ' ')
    11             {
    12                 reverse(p,b);    // C++ 中 algorithms 中的函数,用于反转。
    13                 p = b + 1;       // 更新 迭代器 p
    14             }
    15         }
    16        
    17         s.erase(s.end() -1);     // 去除添加在string最后的空格
    18         return s;
    19     }
    20     
    21     
    pp
  • 相关阅读:
    vue 兄弟组件间传值(bus方式)的坑(重复触发和首次未触发)
    vue 组件间传值(兄弟)(bus方式)
    vue 导出数据到excel
    vue-cli webpack打包后加载资源的路径问题
    vue组件传值之(父子)
    vue组件传值
    thinkphp 5 一些常见问题
    windows 安装 composer
    HTML H5响应式,表格,表单等
    面试
  • 原文地址:https://www.cnblogs.com/wangxiaoyong/p/8651729.html
Copyright © 2011-2022 走看看