Search code examples
c++stdvectorstdlist

accelerated C++ to find longest of palindrome


I am practising Koeing accelerated C++ , and want to verify my answer. Since there are no solutions available on net , I thought to post it here and ask experts view about my solution. I am not sure if people will like me to post it here. if not , please let me know and i will not do it in future. Also to mention, its not homework , its purely my desire to take my C++ skills to next level.

Question: Write a program to find all the palindromes in a dictionary. Next, find the longest palindrome.

What I have done so far -> I have defined function to test palindrome , also stored all words in a list. I have posted my code below.

Where I am stuck: I need advice , whether my choice of using list data structure over vector is good or not? Secondly, I am stuck how to display longest word. I can display longest length but not longest word.

my attempt below

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

Solution

  • Vectors and lists both work equally well here, though a vector is more efficient.

    You can find the longest word by changing

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

    to

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

    (You don't actually need to keep track of maxlen since you can just call longestWord.size().)