522. 最长特殊序列 II
给定字符串列表 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]
只包含小写英文字母
class Solution:
def findLUSlength(self, strs: List[str]) -> int:
#判断s是否是t的子串
def is_subseq(s: str, t: str) -> bool:
pt_s = pt_t = 0#双指针
while pt_s < len(s) and pt_t < len(t):
if s[pt_s] == t[pt_t]:
pt_s += 1
pt_t += 1
return pt_s == len(s)#判断s是否已经遍历完,遍历完则是子串
ans = -1
#enumerate在字典上是枚举、列举的意思 enumerate参数为可遍历/可迭代的对象(如列表、字符串)
#enumerate多用于在for循环中得到计数,利用它可以同时获得索引和值,即需要index和value值的时候可以使用enumerate
#enumerate()返回的是一个enumerate对象
for i, s in enumerate(strs):#遍历str列表
check = True#是否是特殊序列
for j, t in enumerate(strs):
if i != j and is_subseq(s, t):#判断s是否是t的子串
check = False
break
if check:
ans = max(ans, len(s))
return ans