Question
Implement a function bool chainable(vector
, which takes a set of strings as parameters and returns true
if they
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;
}
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.