Skip to content

Commit 0cdd3b3

Browse files
committed
Sync LeetCode submission Runtime - 42 ms (21.17%), Memory - 16.5 MB (50.23%)
1 parent ce75b76 commit 0cdd3b3

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

0409-longest-palindrome/README.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<p>Given a string <code>s</code> which consists of lowercase or uppercase letters, return the length of the <strong>longest <span data-keyword="palindrome-string">palindrome</span></strong>&nbsp;that can be built with those letters.</p>
2+
3+
<p>Letters are <strong>case sensitive</strong>, for example, <code>&quot;Aa&quot;</code> is not considered a palindrome.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> s = &quot;abccccdd&quot;
10+
<strong>Output:</strong> 7
11+
<strong>Explanation:</strong> One longest palindrome that can be built is &quot;dccaccd&quot;, whose length is 7.
12+
</pre>
13+
14+
<p><strong class="example">Example 2:</strong></p>
15+
16+
<pre>
17+
<strong>Input:</strong> s = &quot;a&quot;
18+
<strong>Output:</strong> 1
19+
<strong>Explanation:</strong> The longest palindrome that can be built is &quot;a&quot;, whose length is 1.
20+
</pre>
21+
22+
<p>&nbsp;</p>
23+
<p><strong>Constraints:</strong></p>
24+
25+
<ul>
26+
<li><code>1 &lt;= s.length &lt;= 2000</code></li>
27+
<li><code>s</code> consists of lowercase <strong>and/or</strong> uppercase English&nbsp;letters only.</li>
28+
</ul>
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Approach 1: Greedy Way (Hash Table)
2+
3+
# Time: O(n)
4+
5+
class Solution:
6+
def longestPalindrome(self, s: str) -> int:
7+
freq = {}
8+
9+
for c in s:
10+
freq[c] = freq.get(c, 0) + 1
11+
12+
res = 0
13+
has_odd_freq = False
14+
15+
for f in freq.values():
16+
if (f % 2) == 0:
17+
res += f
18+
19+
else:
20+
# If the frequency is odd, one occurrence of the
21+
# character will remain without a match
22+
res += f - 1
23+
has_odd_freq = True
24+
25+
# If has_odd_frequency is true, we have at least one unmatched
26+
# character to make the center of an odd length palindrome.
27+
if has_odd_freq:
28+
return res + 1
29+
30+
return res
31+

0 commit comments

Comments
 (0)