原题地址:https://leetcode-cn.com/problems/longest-uncommon-subsequence-ii/
题目描述:
给定字符串列表,你需要从它们中找出最长的特殊序列。最长特殊序列定义如下:该序列为某字符串独有的最长子序列(即不能是其他字符串的子序列)。
子序列可以通过删去字符串中的某些字符实现,但不能改变剩余字符的相对顺序。空序列为所有字符串的子序列,任何字符串为其自身的子序列。
输入将是一个字符串列表,输出是最长特殊序列的长度。如果最长特殊序列不存在,返回 -1 。
示例:
输入: "aba", "cdc", "eae"
输出: 3
提示:
所有给定的字符串长度不会超过 10 。
给定字符串列表的长度将在 [2, 50 ] 之间。
解题方案:
all() 函数用于判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE,如果是返回 True,否则返回 False。
元素除了是 0、空、None、False 外都算 True。
对应的还有any()函数。。
from collections import Counter
class Solution:
def findLUSlength(self, strs: List[str]) -> int:
def is_sub(behind, front):
if behind == front:
return True
idx = 0
for i in front:
if idx < len(behind) and behind[idx] == i:
idx += 1
return idx == len(behind)
cnt = Counter(strs)
strs = sorted(cnt.keys(), key = len, reverse = True)
for i, w in enumerate(strs):
if cnt[w] == 1 and all(not is_sub(w,front) for front in strs[:i]):
return len(w)
return -1