剑指offer-面试题58_1-翻转单词顺序-字符串

/*
题目:
	输入一个英文句子,翻转单词顺序,但单词内部顺序不变。
*/
/*
思路:
	先翻转整个句子,再将每个单词分别翻转一次。
*/
#include<iostream>
#include<cstring>
#include<vector>
#include<algorithm>
#include<map>

using namespace std;

void verse(char* pBegin,char* pEnd){
    while(pEnd > pBegin){

        char temp = *pBegin;
        *pBegin = *pEnd;
        *pEnd = temp;
        pBegin++;
        pEnd--;
    }
}

char* ReverseSentence(char* pData){
    char* pBegin = pData;
    char* pEnd = pData;
    while(*pEnd != ''){
        pEnd++;
    }
    pEnd--;
    verse(pBegin,pEnd);
    char* res = pData;


    pBegin = pEnd = pData;
    while(*pBegin != ''){
        if(*pBegin == ' '){
            pBegin++;
            pEnd++;
        }else if(*pEnd == ' ' || *pEnd == ''){
            verse(pBegin,--pEnd);
            pBegin = ++pEnd;
        }else{
            pEnd++;
        }
    }
    return pData;

}

int main(){
   char pData[] = "I am a student.";
   char* res = ReverseSentence(pData);
   while(*res != ''){
        cout<<*res;
        res++;
   }
}

  

原文地址:https://www.cnblogs.com/buaaZhhx/p/12109528.html