Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions 0409.Longest-Palindrome/memo.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# 409. Longest Palindrome

## step1
解くだけなら 5分ぐらい

## step2

Counterで書き直す、変数名の改善

> 正攻法でないものとして、Manacher's algorithm というのがあります。

別の問題の解法

https://leetcode.com/problems/longest-palindromic-substring/description/?envType=problem-list-v2&envId=rab78cw1

(忘れていたので書き直していても良いかもしれない)

https://github.com/Kitaken0107/GrindEasy/pull/27#discussion_r1656471861

https://github.com/huyfififi/coding-challenges/pull/17

https://github.com/NobukiFukui/Grind75-ProgrammingTraining/pull/31

https://github.com/ryosuketc/leetcode_grind75/pull/17

おおむね同じ解法だが 1 pathの書き方を真似しておく。 最後は `len(s) - odd_count + 1`としている。
14 changes: 14 additions & 0 deletions 0409.Longest-Palindrome/step1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
class Solution:
def longestPalindrome(self, s: str) -> int:
char_to_count = {}
for c in s:
char_to_count[c] = char_to_count.setdefault(c, 0) + 1

exist_odd_count = False
half_length = 0
for c, count in char_to_count.items():
half_length += count // 2
if count % 2 == 1:
exist_odd_count = True

return half_length * 2 if not exist_odd_count else half_length * 2 + 1
35 changes: 35 additions & 0 deletions 0409.Longest-Palindrome/step2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from collections import Counter


class Solution:
def longestPalindrome(self, s: str) -> int:
counts = Counter(s)
length = 0
has_odd_count = False

for count in counts.values():
length += (count // 2) * 2
if count % 2 == 1:
has_odd_count = True

return length + 1 if has_odd_count else length


from collections import defaultdict


class Solution:
def longestPalindrome(self, s: str) -> int:
char_to_count = defaultdict(int)
odd_count = 0

for c in s:
char_to_count[c] += 1
if char_to_count[c] % 2 == 1:
odd_count += 1
else:
odd_count -= 1

if odd_count <= 1:
return len(s)
return len(s) - odd_count + 1