假设我们有一个字符串单词列表。我们必须制作一个字符串,该字符串是通过串联单词的子序列构成的,以便每个字母都是唯一的。我们最终必须找到最长的这种串联的长度。
因此,如果输入像单词= [“ xyz”,“ xyw”,“ wab”,“ cde”],则输出将为9,因为我们不能选择任何单词,因为它们包含重复的字符。
为了解决这个问题,我们将按照以下步骤
回答:= 0
定义一个功能recur()
。这将使i:= 0,cur:=空字符串
if i is same as size of words , then ans := maximum of ans and size of cur return recur(i + 1, cur) if all characters in words[i] are unique and all characters in (cur + words[i]) are unique, then recur(i + 1, cur + words[i]) From the main method do the following: recur() return ans
让我们看下面的实现以更好地理解:
class Solution: def solve(self, words): ans = 0 def is_all_unique(s): return len(set(s)) == len(s) def recur(i=0, cur=""): nonlocal ans if i == len(words): ans = max(ans, len(cur)) return recur(i + 1, cur) if is_all_unique(words[i]) and is_all_unique(cur + words[i]): recur(i + 1, cur + words[i]) recur() return ans ob = Solution()words = ["xyz", "xyw", "wab", "cde"] print(ob.solve(words))
["xyz", "xyw", "wab", "cde"]
输出结果
9