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     

 

转载于:https://www.cnblogs.com/wangxiaoyong/p/8651729.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值