522. 最长特殊序列 II
难度中等121
给定字符串列表 strs
,返回其中 最长的特殊序列 。如果最长特殊序列不存在,返回 -1
。
特殊序列 定义如下:该序列为某字符串 独有的子序列(即不能是其他字符串的子序列)。
s
的 子序列可以通过删去字符串 s
中的某些字符实现。
- 例如,
"abc"
是"aebdc"
的子序列,因为您可以删除"aebdc"
中的下划线字符来得到"abc"
。"aebdc"
的子序列还包括"aebdc"
、"aeb"
和 “” (空字符串)。
示例 1:
输入: strs = ["aba","cdc","eae"]
输出: 3
示例 2:
输入: strs = ["aaa","aaa","aa"]
输出: -1
提示:
2 <= strs.length <= 50
1 <= strs[i].length <= 10
strs[i]
只包含小写英文字母
//题目要求即找到最长特殊子串返回子串长度(这个字串可以是字符串自己)
//特殊意味着不是其他字符串的子串
因此编写判断字串的函数
再对strs这个字符串序列进行遍历,找到所有不是其他字符串子串的字符串的最大长度返回
#include <iostream>
#include <stdlib.h>
#include <vector>
using namespace std;
class solution
{
public:
int findLUSlength(vector<string> &strs)
{
int ans = -1;
int n = strs.size();
for (int i = 0; i < n; i++)
{
bool judge = true;
for (int j = 0; j < n; j++)
{
if (i != j && check(strs[i], strs[j]))
{
judge = false;
break;
}
}
if (judge)
{
ans = max(ans, static_cast<int>(strs[i].size())); //这里必须类型强制转换,不然无法使用max函数
}
}
}
bool check(string str1, string str2) //判断str1是否为str2子串
{
int i = 0; // str1长度短
int j = 0; // str2长度长
while (i < str1.size() && j < str2.size())
{
if (str1[i] == str2[j])
{
i++;
j++;
}
else
{
j++;
}
}
return i == str1.size();
}
};
int main()
{
vector<string> strs;
strs.push_back("def"); //把字符串"def"压进容器
cout << strs[0].size() << endl;
cout << typeid(strs[0].size()).name() << endl;
system("pause");
return 0;
}