44、剑指offer--翻转单词顺序列

题目描述
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
 
解题思路:先将整个字符串进行完全翻转,然后再翻转每个单词
 1 class Solution {
 2 public:
 3     void Reverse(char *pStart, char *pEnd)
 4     {
 5         if(pStart == NULL || pEnd == NULL)
 6             return;
 7         while(pStart < pEnd)
 8         {
 9             char tmp = *pStart;
10             *pStart = *pEnd;
11             *pEnd = tmp;
12             pStart++;
13             pEnd--;
14         }
15     }
16     string ReverseSentence(string str) {
17         if(str.empty())
18             return str;//此处不能直接return NULL
19         int length = str.size();
20         char *pStart = &str[0];
21         char *pEnd = &str[length-1];
22         //翻转整个字符串
23         Reverse(pStart,pEnd);
24         //翻转每个单词
25         pStart = pEnd = &str[0];//初始设置
26         while(*pStart != '')
27         {
28             if(*pStart == ' ')//一个单词结束,进入下一单词
29             {
30                 pStart++;
31                 pEnd++;
32             }
33             else if(*pEnd == ' ' || *pEnd == '')//到达一个单词结尾,或者整个字符串结尾,进行翻转
34             {
35                 Reverse(pStart,--pEnd);//把pEnd移动到指向单词的最后一个字母
36                 pStart = ++pEnd;//起始结束都变到处理的这个单词最后的下一个位置
37             }
38             else//未找到一个单词的结尾
39             {
40                 pEnd++;
41             }
42         }
43         return str;
44     }
45 };
原文地址:https://www.cnblogs.com/qqky/p/7018472.html