2131. Longest Palindrome by Concatenating Two Letter Words,兩兩字串形成回文

 You are given an array of strings words. Each element of words consists of two lowercase English letters.

Create the longest possible palindrome by selecting some elements from words and concatenating them in any order. Each element can be selected at most once.

Return the length of the longest palindrome that you can create. If it is impossible to create any palindrome, return 0.

palindrome is a string that reads the same forward and backward.

 

Example 1:

Input: words = ["lc","cl","gg"]
Output: 6
Explanation: One longest palindrome is "lc" + "gg" + "cl" = "lcggcl", of length 6.
Note that "clgglc" is another longest palindrome that can be created.

Example 2:

Input: words = ["ab","ty","yt","lc","cl","ab"]
Output: 8
Explanation: One longest palindrome is "ty" + "lc" + "cl" + "yt" = "tylcclyt", of length 8.
Note that "lcyttycl" is another longest palindrome that can be created.

Example 3:

Input: words = ["cc","ll","xx"]
Output: 2
Explanation: One longest palindrome is "cc", of length 2.
Note that "ll" is another longest palindrome that can be created, and so is "xx".

 

Constraints:

  • 1 <= words.length <= 105
  • words[i].length == 2
  • words[i] consists of lowercase English letters.


分兩類
第一類兩個字不同 像是"ab"
第二類兩個字相同 像是"cc"


之後走一遍: 看ab 有沒有ba跟他配 有的話 長度+4 ab, ba數量各自少1

之後走single words:

最後一個單獨single words 假設剩下一個gg
那也可以+2

即可

class Solution:
    def longestPalindrome(self, words: List[str]) -> int:
        
        
        d=dict()
        single=dict()
        for i in words:
            if i[0]!=i[1]:
                d[i]=d.get(i,0)+1
            else:
                single[i]=single.get(i,0)+1
        
        
        res=0
        for i in words:
            if i[0]!=i[1]:    
                if (i[::-1]) in d and d[i[::-1]]>0 and d[i]>0:
                    res+=4
                    d[i]-=1
                    d[i[::-1]]-=1
            # single words
            else:
                if (i[::-1]) in single and single[i[::-1]]>=2:
                    res+=4
                    single[i]-=2
        
        
        if single.values() and max(single.values())>=1:
            return res+2
        else:
            return res
                
        
    

留言

這個網誌中的熱門文章

1041. Robot Bounded In Circle 機器人在圈圈裏面?

382. Linked List Random Node: 隨機選元素從list裡面

2134. Minimum Swaps to Group All 1's Together II 使得所有1連在一起