[C/C++程式設計師面試寶典] (07)-翻轉句子中單詞的順序
題目:輸入一個英文句子,翻轉句子中單詞的順序,但單詞內字元的順序不變。句子中單詞以空格符隔開。為簡單起見,標點符號和普通字母一樣處理。
例如輸入“I am a student.”,則輸出“student. a am I”。
分析:由於編寫字串相關程式碼能夠反映程式設計師的程式設計能力和程式設計習慣,與字串相關的問題一直是程式設計師筆試、面試題的熱門題目。本題也曾多次受到包括微軟在內的大量公司的青睞。
由於本題需要翻轉句子,我們先顛倒句子中的所有字元。這時,不但翻轉了句子中單詞的順序,而且單詞內字元也被翻轉了。我們再顛倒每個單詞內的字元。由於單詞內的字元被翻轉兩次,因此順序仍然和輸入時的順序保持一致。
還是以上面的輸入為例子。翻轉“I am a student.”中所有字元得到“.tneduts a ma I”,再翻轉每個單詞中字元的順序得到“students. a am I”,正是符合要求的輸出。
參考程式碼:
///////////////////////////////////////////////////////////////////////
// Reverse a string between two pointers
// Input: pBegin - the begin pointer in a string
// pEnd - the end pointer in a string
///////////////////////////////////////////////////////////////////////
void Reverse(char*pBegin, char *pEnd)
{
if(pBegin== NULL || pEnd == NULL)
return;
while(pBegin< pEnd)
{
chartemp = *pBegin;
*pBegin = *pEnd;
*pEnd = temp;
pBegin ++, pEnd --;
}
}
///////////////////////////////////////////////////////////////////////
// Reverse the word order in a sentence, but maintain the character
// order inside a word
// Input: pData - the sentence to be reversed
///////////////////////////////////////////////////////////////////////
char* ReverseSentence(char *pData)
{
if(pData== NULL)
returnNULL;
char*pBegin = pData;
char*pEnd = pData;
while(*pEnd!= '\0')
pEnd ++;
pEnd--;
// Reversethe whole sentence
Reverse(pBegin, pEnd);
// Reverseevery word in the sentence
pBegin = pEnd = pData;
while(*pBegin!= '\0')
{
if(*pBegin== ' ')
{
pBegin ++;
pEnd ++;
continue;
}
// A wordis between with pBegin and pEnd, reverse it
elseif(*pEnd == ' '|| *pEnd == '\0')
{
Reverse(pBegin, --pEnd);
pBegin = ++pEnd;
}
else
{
pEnd ++;
}
}
returnpData;
}