Synthesis of the longest string

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/iov3Rain/article/details/90414905

Title Description

There is a group of words, write a program to find the longest string in the array A by the strings in the array, i.e., A is a (reproducible) longest word composed of other words.

Given an array of string str, while the size of the array given n. Please return the length of the longest word, the longest word in the title is intended to ensure the existence.

Test sample:

["a","b","c","ab","bc","abc"],6

Returns: 3

 

class LongestString
{
public:
    int ans = 0;
    map<string, bool> hash;
    int maxlen = 0;
    int getLongest(vector<string> str, int n)
    {
        // write code here
        for (int i = 0; i < str.size(); ++i)
        {
            hash[str[i]] = true;
            maxlen = maxlen > str[i].size() ? maxlen : str[i].size();
        }
        for (int i = 0; i < n; ++i)
        {
            fun(str, str[i]);
        }
        return ans;
    }

    void fun(vector<string> &str, string cur)
    {
        for (int i = 0; i < str.size(); ++i)
        {
            string temp = cur + str[i];
            if (temp.size() > maxlen)
            {
                continue;
            }
            else if (temp.size() == maxlen)
            {
                if (hash[temp] == true)
                {
                    ans = temp.size() > ans ? temp.size() : ans;
                }
            }
            else
            {
                if (hash[temp] == true)
                {
                    ans = temp.size() > ans ? temp.size() : ans;
                    fun(str, temp);
                }
            }
        }
    }
};

 

Guess you like

Origin blog.csdn.net/iov3Rain/article/details/90414905