![]() ![]() ![]() ![]() |
|||||
|
|||||
樓主 Mercy ![]()
![]() |
-------------------------------------------------------------------------------- Palindrome(中文譯做"迴文")是西方的一種文字游戲,指的是一段文字由左至右或是由右至左的字母出現的順序都一樣,也就是其字元是前後對稱的;例如 God saw I was dog. "I Love Me, Vol. I." Nipson anomemata me monan ospin (希臘文:不僅洗你的臉,也洗你的罪) 都是典型的 palindrome. 在 http://www.palindromes.org/ 還可以找到更多的 palindrome. 當然在 palindrome 的判斷標準中是不考慮空白與標點符號,只有考慮字母,而且也忽略大小寫的差異.利用 recursive方法,我們可以寫一個 C++ 程式來判斷一個句子是否屬於 palindrome.首先必須要把字串中的所有非字母字元去除,只留下字母字元;而且所有字母字元都要統一轉換成大寫(或小寫)以方便程式判斷.判斷的方法如下: 一個字串長度為 0 或 1,則這個字串當然是 palindrome 一個字串長度為大於 1,則這個字串第一個與最後一個字元必須相同,而且這個字串去除第一個與最後一個字元後仍然是屬於 palindrome 參考程式 //anagram.cpp //creates anagrams #include <iostream> #include <string> using namespace std; //////////////////////////////////////////////////////////////// class word { private: int size; //length of input word int count; //numbers in display string workStr; //workspace void rotate(int); //rotate part of workStr void displayWord(); //display workStr public: word(string); //constructor void anagram(int); //anagram ourselves }; //-------------------------------------------------------------- //constructor word::word(string inpStr) : workStr(inpStr), count(0) { //initialize workStr size = inpStr.length(); //number of characters } //-------------------------------------------------------------- void word::anagram(int newSize) { if(newSize == 1) //if too small, return; //go no further for(int j=0; j<newSize; j++) //for each position, { anagram(newSize-1); //anagram remaining if(newSize==2) //if innermost, displayWord(); // display it rotate(newSize); //rotate word } } //-------------------------------------------------------------- //rotate left all chars from position to end void word::rotate(int newSize) { int j; int position = size - newSize; char temp = workStr[position]; //save first letter for(j=position+1; j<size; j++) //shift others left workStr[j-1] = workStr[j]; workStr[j-1] = temp; //put first on right } //-------------------------------------------------------------- void word::displayWord() { if(count < 99) //spaces before one- cout << " "; //or two-digit numbers if(count < 9) cout << " "; cout << ++count << " "; //number cout << workStr << " "; if(count%6 == 0) cout << endl; } //////////////////////////////////////////////////////////////// int main() { string input; int length; cout << "Enter a word: "; //get word cin >> input; length = input.length(); //get its length word theWord(input); //make a word object theWord.anagram(length); //anagram it return 0; } //end main()
本篇文章發表於2005-03-17 15:50
|