剑指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 != '\0'){ pEnd++; } pEnd--; verse(pBegin,pEnd); char* res = pData; pBegin = pEnd = pData; while(*pBegin != '\0'){ if(*pBegin == ' '){ pBegin++; pEnd++; }else if(*pEnd == ' ' || *pEnd == '\0'){ verse(pBegin,--pEnd); pBegin = ++pEnd; }else{ pEnd++; } } return pData; } int main(){ char pData[] = "I am a student."; char* res = ReverseSentence(pData); while(*res != '\0'){ cout<<*res; res++; } }
标签:面试题,58,offer,++,pData,char,pBegin,pEnd,include 来源: https://www.cnblogs.com/buaaZhhx/p/12109528.html