《剑指offer》翻转单词顺序列

本题来自《剑指offer》 翻转单词顺序列

题目:

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

思路:

   1.先翻转整个字符

  2.翻转单个字符

  只需要找到要翻转字符的始末下标即可。

  单个字符要以单词之间的空格作为分割条件。先检测起始是否到达空格,否则便后标自加到单词末尾,到了单词的末尾,便开始翻转,并开始下个单词的翻转。

C++ Code:

class Solution {
public:
    string ReverseSentence(string str) {
        if (str.size()<=0){                        //boundary condition judgement
            return "";                             //return empty string
        }
        char* begin = &str[0];                    //get first point
        char* end = begin;                        //initial end point equal first point
        while(*end!='\0'){                        //get the last point of str
            end++;
        }
        end--;
        Reverse(begin,end);                       //reverse all str
        begin = &str[0];                          //reinitial vartion vaule
        end = begin;
        while(*begin!='\0'){                      //loop condition
            if(*begin==' '){                      //single character
                begin++;
                end++;
            }else if(*end=='\0'||*end==' '){      //at the end of one of the characters
                Reverse(begin,--end);             //reverse one character
                begin = ++end;                    //restart
            }else{
                end++;                            //get one of the characters
            }
        }
        return str;
    }
    void Reverse(char* begin,char* end){         //program of reverse
        if (begin==NULL || end==NULL){           //empty pointer detection
            return ;                             //return NULL
        }
        while(begin<end){
            char temp =*begin;                   //swap the character
            *begin = *end;
            *end = temp;
            begin++;                             //pointer increase
            end--;
        }
    }
};

Python Code:

# -*- coding:utf-8 -*-
class Solution:
    def ReverseSentence(self, s):
        # write code here
            word_s = s.split(' ')
            return ' '.join(word_s[::-1])

总结:

posted @ 2019-04-28 14:23  weilongyitian  阅读(416)  评论(0编辑  收藏  举报