九度:http://ac.jobdu.com/problem.php?pid=1361
10. 翻轉句子中單詞的順序。
題目:輸入一個英文句子,翻轉句子中單詞的順序,但單詞內字符的順序不變。句子中單詞以空格符隔開。爲簡單起見,標點符號和普通字母一樣處理。
例如輸入“I am a student.”,則輸出“student. a am I”。
#include <cstdlib>
#include <iostream>
#include <stdio.h>
using namespace std;
void Reverse(char *pBegin, char *pEnd)
{
if(pBegin == NULL || pEnd == NULL)
return;
while(pBegin < pEnd)
{
char temp = *pBegin;
*pBegin = *pEnd;
*pEnd = temp;
pBegin++;
pEnd--;
}
}
char *ReverseSentence(char *pData)
{
if(pData == NULL)
return NULL;
char *pBegin = pData;
char *pEnd = pData;
while(*pEnd != '\0')
pEnd++;
pEnd--;
//先翻轉整個句子中的所有字符
Reverse(pBegin, pEnd);
pBegin = pEnd = pData;
//翻轉每一個單詞內的字符
while(*pBegin != '\0')
{
if(*pBegin == ' ')
{
pBegin++;
pEnd++;
continue;
}
else if(*pEnd == ' ' || *pEnd == '\0')
{
//cout << "before: " << *pBegin << " " << *(pEnd-1) << endl;
Reverse(pBegin, --pEnd);
//cout << "after: " << *pBegin << " " << *pEnd << endl;
pBegin = ++pEnd;
}
else
{
pEnd++;
}
}
return pData;
}
int main()
{
/*
char a[5001] = {"I am a student."};
char *pData = &a[0];
ReverseSentence(pData);
cout << pData << endl;
*/
char *pData;
char a[500001];
while(gets(a))
{
pData = &a[0];
ReverseSentence(pData);
//cout << pData << endl;
puts(a);
}
return EXIT_SUCCESS;
}