题目
给定字符串列表 strs ,返回其中 最长的特殊序列 。如果最长特殊序列不存在,返回 -1 。
特殊序列 定义如下:该序列为某字符串 独有的子序列(即不能是其他字符串的子序列)。
s 的 子序列可以通过删去字符串 s 中的某些字符实现。
例如,"abc" 是 "aebdc" 的子序列,因为您可以删除"aebdc"中的下划线字符来得到 "abc" 。"aebdc"的子序列还包括"aebdc"、 "aeb" 和 "" (空字符串)。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/longest-uncommon-subsequence-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
示例
思路
题目的大意是,在字符串列表strs中,找到最长的并且这个字符串不是strs中任意字符串的子串
其中strs中长度最长并且唯一,那么这个字符串肯定是满足要求,
我们可以定义双指针,一个i遍历strs列表元素,另外一个j遍历strs列表查看i是否存在strs列表元素的子串中,存在i++,不存在则将i的长度保存,最后输出最大值
代码
#define MAX(a,b) (a) > (b) ? (a) : (b)
/*
*int ifstr(char * a, char * b)
int ifstr:判断a字符串是否为b字符串的子串
char * a:字符串a
char * b:字符串b
返回值:是返回 1,不是返回 0
*/
int ifstr(char * a, char * b)
{
int a_len = strlen(a);
int b_len = strlen(b);
int a_i = 0, b_i = 0;
while(a_i < a_len && b_i < b_len)
{
if(a[a_i] == b[b_i])
{
a_i++;
}
b_i++;
}
return a_i == a_len ? 1 : 0;
}
/*
int findLUSlength(char ** strs, int strsSize)
*int findLUSlength:给定字符串列表 strs ,找其中 最长的特殊序列
char ** strs:字符串列表
int strsSize:字符串列表的长度
返回值:返回其中 最长的特殊序列
*/
int findLUSlength(char ** strs, int strsSize){
int i, j;
int res = -1;
for(i = 0; i < strsSize; i++)
{
int t = 1;
for(j = 0; j < strsSize ; j++)
{
if(ifstr(strs[i] , strs[j]) == 1 && j != i)
{
t = 0;
break;
}
}
if(t == 1)
res = MAX(res, (int )strlen(strs[i]));
}
return res;
}
时间空间复杂度