题目描述
有一组单词,请编写一个程序,在数组中找出由数组中字符串组成的最长的串A,即A是由其它单词组成的(可重复)最长的单词。
给定一个string数组str,同时给定数组的大小n。请返回最长单词的长度,保证题意所述的最长单词存在。
测试样例:
["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);
}
}
}
}
};