iT邦幫忙

2021 iThome 鐵人賽

DAY 22
0
自我挑戰組

每日LeetCode解題紀錄系列 第 22

LeetCode解題 Day22

1239. Maximum Length of a Concatenated String with Unique Characters

https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/


題目解釋

你會得到一個裝滿字串的陣列arr,請用arr中的字串組合一個沒有任何字母重複的字串s

請回傳所有可能的組合中最長的長度。

example

https://i.imgur.com/hRGGnxm.png


解法

這題的解法是要從arr中找出所有符合條件的字串,並讓符合條件的字串和其他字串做組合

程式碼

class Solution:
    def maxLength(self, arr: List[str]) -> int:
        
        unique = ['']
        ans = 0
        
        for i in range(len(arr)):
            
            for j in range(len(unique)):
                
                word = arr[i] + unique[j]
                
                if len(word) == len(set(word)):
                    unique.append(word)
                    ans = max(ans, len(word))
        return ans

閒聊

今天的題目除了上面的解法外,還有很多種解法,可用dp、backtracking甚至還有bit-manipulation

一題可以滿足多種練習需求


上一篇
LeetCode解題 Day21
下一篇
LeetCode解題 Day23
系列文
每日LeetCode解題紀錄30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言