Python程式:查詢唯一字元連線字串的長度?
假設我們有一組字串words。我們需要構造一個字串,該字串透過連線words的子序列構成,並且每個字母都是唯一的。最終我們需要找到最長此類連線的長度。
因此,如果輸入類似於words = ["xyz", "xyw", "wab", "cde"],則輸出將為9,因為我們無法選擇任何單詞,因為它們包含重複的字元。
為了解決這個問題,我們將遵循以下步驟
ans := 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
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP