程序员面试题精选100题(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){char temp = *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)return NULL;char *pBegin = pData;char *pEnd = pData;while(*pEnd != '\0')pEnd ++;pEnd--;// Reverse the whole sentenceReverse(pBegin, pEnd);// Reverse every word in the sentencepBegin = pEnd = pData;while(*pBegin != '\0'){if(*pBegin == ' '){pBegin ++;pEnd ++;continue;}// A word is between with pBegin and pEnd, reverse itelse if(*pEnd == ' ' || *pEnd == '\0'){Reverse(pBegin, --pEnd);pBegin = ++pEnd;}else{pEnd ++;}}return pData; }????????????
本文已經收錄到《劍指Offer——名企面試官精講典型編程題》一書中,有改動,書中的分析講解更加詳細,討論了這個題目和左旋轉字符串的聯系,舉一反三。歡迎關注。本文的英文版詳見http://codercareer.blogspot.com/2011/09/no-07-reverse-words-in-sentence.html,歡迎感興趣的朋友閱讀并批評指正。
本題已被九度Online Judge系統收錄,歡迎讀者移步到http://ac.jobdu.com/hhtproblems.php在線測試自己的代碼。
博主何海濤對本博客文章享有版權。網絡轉載請注明出處http://zhedahht.blog.163.com/。整理出版物請和作者聯系。
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的程序员面试题精选100题(07)-翻转句子中单词的顺序[算法]的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 程序员面试题精选100题(06)-二元查
- 下一篇: 程序员面试题精选100题(08)-求1+
