最も長い文字列の合成

免責事項:この記事はブロガーオリジナル記事ですが、許可ブロガーなく再生してはなりません。https://blog.csdn.net/iov3Rain/article/details/90414905

タイトル説明

単語のグループがあり、即ちアレイ内の文字列で配列Aの中で最も長い文字列を検索するプログラムを書いて、Aは、他のワードの構成(再現)最長の単語です。

アレイのサイズはN与えながら、文字列strのアレイを考えます。最も長い単語の長さを返してください、タイトルの中で最も長い単語が存在することを確実にするためのものです。

試験サンプル:

[ "A"、 "B"、 "C"、 "AB"、 "BC"、 "ABC"]、6

戻り値: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);
                }
            }
        }
    }
};

 

おすすめ

転載: blog.csdn.net/iov3Rain/article/details/90414905