엔지니어 게시판
LeetCode 솔루션 분류

[11/3] 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.
Accepted
79,339
Submissions
161,342
태그

관련자료

댓글 1

학부유학생님의 댓글

  • 익명
  • 작성일
Runtime: 1487 ms, faster than 86.73% of Python3 online submissions for Longest Palindrome by Concatenating Two Letter Words.
Memory Usage: 38.4 MB, less than 25.84% of Python3 online submissions for Longest Palindrome by Concatenating Two Letter Words.
from collections import Counter
class Solution:
    def longestPalindrome(self, words: List[str]) -> int:
        counter = Counter(words)
        center = 0
        palin_diff = 0
        palin_same = 0
        
        for word, count in counter.items():
            if word[0]==word[1]:
                palin_same += count//2*2
                
                if count%2==1: center =2
            
            else:
                palin_diff += min(counter[word], counter[word[::-1]])*0.5
        
        return palin_same*2 + int(palin_diff)*4 + center
                
                
                
전체 404 / 1 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


알림 0