/* * Accelerated C++ P104 习题5.10 * 回文是指一种顺读和倒读都一样的单词。编写一个程序,让他找出一个单词集中的所有回文并且找出最长的回文 * 输入: const vector<string>& words 单词集 * 输出:返回值 vector<string> 所有回文的集合 通过引用参数返回 string& lengthest_word 最长的回文 */ #include<iostream> #include<vector> #include<string> #include<stdio.h> #include<stdlib.h> using std::vector; using std::string; using std::cin; using std::cout; using std::endl; bool ispalindrome(const string& str) { int k = str.size(); for(int i = 0;i != k/2; i++) { if(str[i] != str[k-i-1]) { return false; } } return true; } vector<string> gene_palindrome(const vector<string>& words, string& lengthest_word) { vector<string> ret; int length = 0; for(vector<string>::const_iterator iter = words.begin(); iter != words.end(); iter++) { if(ispalindrome(*iter)) { if(iter->size() > length) { length = iter->size(); lengthest_word = *iter; } ret.push_back(*iter); } } return ret; } int main(void) { freopen("data.txt","r",stdin); vector<string> words; string word; while(cin>>word) { words.push_back(word); } string lengthest_word; vector<string> ret = gene_palindrome(words,lengthest_word); cout<<"all the palindromes:"<<endl; for(vector<string>::iterator iter = ret.begin(); iter != ret.end(); iter++) { cout<<*iter<<endl; } if(lengthest_word.size() != 0) { cout<<endl<<"the lengthest palindrome:"<<endl; cout<<lengthest_word<<endl; } else { cout<<endl<<"there is no palindrome"<<endl; } //while(1); system("PAUSE"); return 0; }