剑指offer-反转单词顺序列

题目描述

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

解题思路

第一步反转句子中所有的字符,比如反转上例可得:“.tneduts a ma I”,此时不但反转了句子中单词的顺序,连单词内的字符顺序也被反转了。第二步再反转每个单词中字符的顺序,就得到了“student. a am I”。这正是符合题目要求的输出。

代码

 1 class Solution {
 2 public:
 3     string ReverseSentence(string str) {
 4         int len = str.size();
 5         if(len == 0)
 6             return "";
 7         str = Reverse(str, 0, len-1);
 8         int start = 0, end = 0;
 9         string res = "";
10         while(end <= len){
11             if(str[start] == ' '){
12                 res += " ";
13                 start++;
14             }
15             else if(end == len){
16                 res += Reverse(str, start, end-1);
17             }
18             else if(str[end] == ' '){
19                 res += Reverse(str, start, end-1);
20                 res += " ";
21                 start = end+1;
22             }
23             end++;
24         }
25         return res;
26     }
27     string Reverse(string str, int start, int end){
28         string s = "";
29         while(end >= start){
30             s += str[end];
31             end--;
32         }
33         return s;
34     }
35 };
原文地址:https://www.cnblogs.com/wmx24/p/8691493.html