gpt4 book ai didi

c++ - 加速 C++ 寻找最长的回文

转载 作者:行者123 更新时间:2023-11-28 03:34:26 26 4
gpt4 key购买 nike

我正在练习 Koeing accelerated C++ ,想验证我的答案。由于网上没有可用的解决方案,所以我想把它贴在这里,请专家看一下我的解决方案。我不确定人们是否会喜欢我将它张贴在这里。如果没有,请告诉我,我以后不会这样做。还要提一下,这不是家庭作业,纯粹是我希望将我的 C++ 技能提升到一个新的水平。

问题:写一个程序找出字典中所有的回文。接下来,找到最长的回文。

到目前为止我做了什么 -> 我已经定义了测试回文的函数,还将所有单词存储在一个列表中。我已经在下面发布了我的代码。

我被困在哪里我需要建议,我选择使用列表数据结构而不是 vector 是否好?其次,我不知道如何显示最长的单词。我可以显示最长的长度但不能显示最长的单词。

下面是我的尝试

    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;
}

最佳答案

vector 和列表在这里都同样有效,尽管 vector 更有效。

你可以通过改变找到最长的单词

maxLen = max( maxLen, it->size() );
longestWord = *it ;// need to change code here ?? no idea how

if (it->size() >= longestWord.size()) {longestWord = *it;}

(您实际上不需要跟踪 maxlen,因为您只需调用 longestWord.size()。)

关于c++ - 加速 C++ 寻找最长的回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11489107/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com