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
原文地址:https://www.cnblogs.com/wangxiaoyong/p/8651729.html