Re: [闲聊] 每日LeetCode

楼主: pandix (面包屌)   2022-11-03 10:20:25
2131. Longest Palindrome by Concatenating Two Letter Words
龙大是个回文厨,常常发文教育大家回文的美妙之处。
请帮龙大找出 words 中能组成的最长回文字串长度。word 为长度为 2 的小写字母字串。
如果找不出来的话,龙大可能会做出一些蠢事……
Example 1:
Input: words = ["lc","cl","gg"]
Output: 6
最长回文字串(之一) "lcggcl"
Example 2:
Input: words = ["ab","ty","yt","lc","cl","ab"]
Output: 8
最长回文字串(之一) "tylcclyt"
Example 3:
Input: words = ["cc","ll","xx"]
Output: 2
"cc", "ll", "xx"都是 words 能组成的最长回文字串
思路:
1.因为每个 word 长度都是 2,最后组成的字串一定是由 word 两两相对
而相反的 word 一定是放在首尾相对的位置,可以用 Counter 算出每个 word 出现次数
然后看他和他的相反字能配成几对,长度就能加上对数*4
例如 count["ab"] = 3, count["ba"] = 2 就能配出 ababxxxxxxxxbaba
长度就能加上 min(count["ab"], count["ba"]) * 4 = 8
因为在 iterate word 的时候每种组合会算到两次所以*4可以改成*2就好
2.如果两个字母一样就只能跟自己配,能配的对数是 count[word] / 2
长度是加上 4 * (count[word] // 2) 记得要整数除法
另外如果有一个多出来的可以放在中间,可以随便用 flag 记一下
3.Python code:
class Solution:
def longestPalindrome(self, words: List[str]) -> int:
count = Counter(words)
res = 0
single = 0
for word in count:
if word[0] == word[1]:
res += (count[word] // 2) * 4
single = 2 if count[word]%2 else single
else:
res += min(count[word], count[word[::-1]]) * 2
return res + single
作者: Rushia (みけねこ的鼻屎)   2022-11-03 10:40:00
大师
作者: itoumashiro (佩可咪口爱的结晶)   2022-11-03 11:31:00
笑了

Links booklink

Contact Us: admin [ a t ] ucptt.com