Checking if a list of strings can be chained

后端 未结 8 776
庸人自扰
庸人自扰 2021-01-31 23:45

Question

Implement a function bool chainable(vector v), which takes a set of strings as parameters and returns true if they

相关标签:
8条回答
  • 2021-02-01 00:13

    Here's a simple program to do this iteratively:

    #include <string>
    #include <vector>
    #include <iostream>
    
    using std::vector;
    using std::string;
    
    bool isChained(vector<string> const& strngs)
    {
        if (strngs.size() < 2) return false;      //- make sure we have at least two strings
        if (strngs.front().empty()) return false; //- make sure 1st string is not empty
    
        for (vector<string>::size_type i = 1; i < strngs.size(); ++i)
        {
            string const& head = strngs.at(i-1);
            string const& tail = strngs.at(i);
            if (tail.empty())  return false;
            if (head[head.size()-1] != tail[0])  return false;
        }
    
        return true;
    }
    
    int main()
    {
        vector<string>  chained;
        chained.push_back("ship");
        chained.push_back("petal");
        chained.push_back("lion");
        chained.push_back("nick");
    
        vector<string>  notChained;
        notChained.push_back("ship");
        notChained.push_back("petal");
        notChained.push_back("axe");
        notChained.push_back("elf");
    
        std::cout << (isChained(chained) ? "true" : "false") << "\n";     //- prints 'true'
        std::cout << (isChained(notChained) ? "true" : "false") << "\n";  //- prints 'false'
    
        return 0;
    }
    
    0 讨论(0)
  • 2021-02-01 00:18

    if you replace petal and lion with pawn and label, you still have:
    starts:s,p,l,n
    ends: p,l,n,k

    You're algorithm decides its chainable, but they aren't.
    The problem is you are disconnecting the first and last letters of each word.

    A recursive backtracking or dynamic programming algorithm should solve this problem.

    0 讨论(0)
提交回复
热议问题