私は Koeing アクセラレーテッド C++ を練習しており、自分の答えを検証したいと考えています。net には解決策がないため、ここに投稿して、私の解決策について専門家の意見を聞くことにしました。人々が私がここに投稿することを好むかどうかはわかりません. そうでない場合は、お知らせください。今後は行いません。また、これは宿題ではなく、私の C++ スキルを次のレベルに引き上げたいという純粋な願望です。
問題:辞書にあるすべての回文を見つけるプログラムを作成してください。次に、最長の回文を見つけます。
これまでに行ったこと-> 回文をテストする関数を定義し、すべての単語をリストに保存しました。以下にコードを掲載しました。
私が立ち往生している場所: ベクトルよりもリストデータ構造を使用するという私の選択が良いかどうかに関係なく、アドバイスが必要ですか? 第二に、最も長い単語を表示する方法に行き詰まっています。最長の長さは表示できますが、最長の単語は表示できません。
以下の私の試み
bool palindromeTest( const std::string& input )
{
typedef std::string::size_type strSize;
strSize i = 0;
strSize j = input.size() - 1 ;
while( i < input.size() )
{
if ( input[i] != input[j])
{
return false;
}
i++;
j--;
}
return true;
}
int main()
{
// stores all words in a list or vector
std::list< string> listDict;
std::string readWord;
std::ifstream readFile( "/Users/apple/palidndrome-ch5-10/dict.txt" );
if( ! readFile )
{
std::cout <<" failed to open file" << std::endl;
return 0;
}
while( readFile >> readWord )
{
listDict.push_back( readWord );
}
std::string::size_type maxLen = 0 ;
std::string longestWord = " "; // to store longest palindrome
// print all the palindrome words and also which is longest palindrome.
for( std::list<std::string>::const_iterator it = listDict.begin(); it != listDict.end(); ++it )
{
if( palindromeTest( *it ) )
{
std::cout <<" the word -> " << *it << " is palindrome" << std::endl;
// find max len of palindrome;
maxLen = max( maxLen, it->size() );
longestWord = *it ;// need to change code here ?? no idea how
}
}
std::cout <<" the maximum len is = " << maxLen << std::endl;
std::cout << " the word with maximum length is " << longestWord ; // something is wrong here
return 0;
}