Check String Chaining
/***
You
are given an array of Strings, return TRUE if and only if All the strings can
be connected in one chain.
Condition
for connectivity is , if the last character of one string matches first
character of second string, the two string can be connected.
Example
: String []arr ={"abc", "cde", "cad" ,
"def" , "eac"} will return TRUE coz all strings can be
connected in one chain
"abc"->"cde"->"eac"->"cad"->"def"
Another
Example : String []arr ={"acb" , "cde", "def",
"ead" } returns False coz
"cde"->"ead"->"def" is the possible chain
but “acb” is left out.
Note
: Its not necessary to start with the first String and form the chain, It may
happen that you won’t get a chain if you start with first string but you can
get a
chain
if you Start with any other String. If there exists a possible chain, then your
solution should return True.
In
the second example , if the first String was suppose “fcb” , then a possible
chain would have exists
"cde"->"ead"->"def"->"fcb" so
True.
***/
/**
Idea:
only to check the first item and last item in string
case1:
no connection
data
structure: linked list
**/
#include<iostream>
#include<string>
using namespace std;
bool isChaining(string *str, int sz, int index, int rd, bool *b) {
if(rd == 0) return true;
for(int i = 0; i<sz; i++) {
if(b[i] && str[index].back() == str[i].front()) {
b[i] = false;
if(isChaining(str, sz, i, rd-1, b)) return true;
b[i] = true;
}
}
return false;
}
void main() {
string str[] = {"cde", "cad" , "def" , "eac", "abc" };
int sz = sizeof(str) / sizeof(string);
bool *b = new bool[sz];
memset(b, true, sz);
for (int i = 0; i<sz; i++)
{
b[i] = false;
if(isChaining(str, sz, i, sz-1, b))
cout<<"true"<<endl;
else memset(b, true, sz);
}
}
Comments
Post a Comment