You are given an array of strings, return true if and only if all the strings can be connected in one chain.
The condition for connection is if the last character of one line corresponds to the first character of the second line, then the two lines can be connected .
Example: String []arr ={"abc", "cde", "cad" , "def" , "eac"} will return true , because all lines can be connected in one chain.
"abc"->"cde"->"eac"->"cad"->"def"
Another example: String []arr ={"acb" , "cde", "def", "ead" } returns False , because
"cde"->"ead"->"def" is a possible chain, but "acb" is not taken into account.
Note No need to start from the first line and form a chain. It may happen that you do not get the chain if you start from the first line. You can get a chain if you start from any other line. If there is a possible chain, then your decision should return true.
In the second example, if the first String were to be "fcb" , then there would be a possible chain, "cde"->"ead"->"def"->"fcb" , so True .
POSSIBLE SOLUTION (what I think): consider each line as a Node graph and connect the nodes if the condition is met. After that, the problem boils down to searching,
if there exists a Hamiltonian Cycle in a graph , which is an NP-complete problem.
Anyone suggest any algorithm or any other solutions?
string arrays algorithm data-structures
roger_that
source share