Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2329513

Browse files
committed
2131#2
1 parent 4d2bb1c commit 2329513

File tree

1 file changed

+35
-3
lines changed

1 file changed

+35
-3
lines changed

‎src/2131-LongestPalindromeByConcatenatingTwoLetterWords.py‎

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,46 @@
1212
1313
See:
1414
15-
Time Spent: min
1615
"""
17-
import collections
18-
from typing import List
16+
from tool import *
1917

2018

2119
class Solution:
2220
def longestPalindrome(self, words: List[str]) -> int:
21+
"""
22+
2022年11月3日
23+
Runtime: 1657 ms, faster than 81.22%
24+
Memory Usage: 38.3 MB, less than 86.56%
25+
26+
1 <= words.length <= 10^5
27+
words[i].length == 2
28+
words[i] consists of lowercase English letters.
29+
"""
30+
cnt = collections.Counter(words)
31+
seen = set()
32+
word_set = set(words)
33+
34+
ret = 0
35+
for word in word_set:
36+
if word in seen:
37+
continue
38+
word2 = word[::-1]
39+
seen.add(word)
40+
if word == word2:
41+
l = cnt[word] // 2
42+
ret += l * 4
43+
elif word2 in word_set:
44+
seen.add(word2)
45+
l = min(cnt[word], cnt[word2])
46+
ret += l * 4
47+
for c in string.ascii_lowercase:
48+
w = c * 2
49+
if w in cnt and cnt[w] & 1:
50+
ret += 2
51+
break
52+
return ret
53+
54+
def longestPalindrome2(self, words: List[str]) -> int:
2355
"""
2456
1 <= words.length <= 10^5
2557
words[i].length == 2

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /