解法
参考:https://leetcode.com/problems/longest-uncommon-subsequence-ii/discuss/191666/python3-36ms-beat-100
首先需要知道一个事情,这个最长子序列一定是其中某个单词,可以用反证法证明:
假设最长子序列为
s
,它属于某个单词word
,由于word
是比s
长的子序列,但它却不是最优,说明word
是另一个单词word2
的子序列,那么s
肯定也是另一个单词word2
的子序列,矛盾。
那么我们可以先用Counter去掉相同的单词,然后把unique的单词长度从高到低排序,如果某个单词不是它前面的单词的子序列(它一定不会是后面单词的子序列),并且它只出现了一次,那么这个单词肯定就是我们要找的最长特殊序列了
class Solution(object):
def findLUSlength(self, strs):
"""
:type strs: List[str]
:rtype: int
"""
def subseq(a,b):
if not (len(a)<=len(b) and set(a)<=set(b)):
return False
i = 0
n = len(a)
for c in b:
if i<n:
if c==a[i]:
i += 1
else:
break
return i==n
from collections import Counter
c = Counter(strs)
dstrs = sorted(c.keys(),key=len,reverse=True)
for i,w in enumerate(dstrs):
if c[w]==1 and all(not subseq(w,s) for s in dstrs[:i]):
return len(w)
return -1