題目描述
有一組單詞,請編寫一個程序,在數組中找出由數組中字符串組成的最長的串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);
}
}
}
}
};