一 题目描述
给定一个string数组str及其大小n。请编写一段代码找出该数组中最长的那个字符串,且要求该字符串能由数组中其他的字符串组成(使用的字符串可重复)。请返回满足要求的最长字符串的长度,保证题意所述的最长单词存在。
测试样例: ["a","b","c","ab","bc","abc"],6
返回:3
二 题解
先将字符串数组根据字符串长度进行递减排序,然后遍历字符串数组,对当前字符串首先判断其是否能由数组中其它字符串组成,如果能,返回当前字符串长度,不能返回-1。
class LongestString {
public:
void printstr(vector<string> str,int n)
{
for (int i = 0; i < n; i++) {
cout << str[i] << " ";
}
cout << endl;
}
static bool cmp(string str1, string str2)
{
return str1.size() > str2.size();
}
int getLongest(vector<string> str, int n) {
// write code here
//["a", "b", "c", "ab", "bc", "abc"], 6
sort(str.begin(), str.end(), cmp); //cmp函数必须是static函数
printstr(str, n);//abc ab bc a b c
for (int i = 0; i < n; ++i)
{
string temp = str[i];
int x;
for (int j = i + 1; j < n; ++j)
{
cout << "x=" << temp.find(str[j]) << endl;//查找子串str[j]在字符串temp中的位置
while ((x = temp.find(str[j])) != -1) //字符串temp中存在子串时,4294967295 == -1
{//用while不用if,是存在["glhz","ddthddth","ddth"]这种情况
temp.erase(x, str[j].size());//从字符串中删除子串
cout << "temp :" << temp << endl;
}
}
if (temp.empty()) return str[i].size();
}
return -1;
}
};
int main()
{
vector<string> str = { "a", "b", "c", "ab", "bc", "abc" };
LongestString obj2;
obj2.getLongest(str,6);
return 0;
}
string中find(str)函数用于查找子串str在string中是否出现,如果出现,返回下标,否则返回特定的数,这个数是4294967295,测试发现与-1相等