Блог пользователя wocagav

Автор wocagav, история, 3 года назад, По-английски

There is an array of strings. Suppose there is a string whose last character matches with the first character of another string. In that case those two form a ring. You have the find the maximum length of the ring formed by the strings in the array. Let me explain the problem with an example. Suppose the array of strings is {ear, track, tired, rat, doe}. Here the maximum ring will be ear->rat->tired->doe>ear. So, the length will be 4.

If possible please provide code also .

  • Проголосовать: нравится
  • -8
  • Проголосовать: не нравится

»
3 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Constraints?

  • »
    »
    3 года назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    in linear time.

    • »
      »
      »
      3 года назад, # ^ |
      Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится

      I don't think it can be done in linear time, as essentially you are finding longest cycle in the graph, which has to be exponential according to me or maybe I am missing something.

    • »
      »
      »
      3 года назад, # ^ |
        Проголосовать: нравится 0 Проголосовать: не нравится

      What is the upper bound on the number of strings and the size of the alphabet? This cannot be done in linear time, but it may still be possible. This depends on the number of letters in the alphabet (i.e. is it only lowercase letters, or are uppercase letters allowed?) and on the maximum number of strings.

»
3 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

This is the approach for O(n*n) solution.

First of all, to work with graphs , we have to map strings with some integer(let by index in this problem).

Make the adjacency list as follows:

for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
	if(i==j) continue;
	if(v[i][0] == v[j][(v[j].length()-1)] ) adj[i].push_back(j);
}

Now, by simply traversing in graph, find out the largest possible cycle.

»
3 года назад, # |
  Проголосовать: нравится +3 Проголосовать: не нравится

Build a graph from the strings first. Then the size of the biggest strongly connected component is the answer. I haven't tried yet so I'm not sure whether it's correct or not.