Skip to content

Commit 0f0a31d

Browse files
author
Kohei Asai
authored
409. Longest Palindrome (axross#116)
1 parent 2dc74fd commit 0f0a31d

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

Diff for: solutions/longestPalindrome.test.ts

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import longestPalindrome from "./longestPalindrome";
2+
3+
describe("409. Longest Palindrome", () => {
4+
const TEST_CASES = new Map([
5+
["abccccdd", 7],
6+
["bb", 2],
7+
["aaaAaaaa", 7],
8+
["zeusnilemacaronimaisanitratetartinasiaminoracamelinsuez", 55],
9+
[
10+
"civilwartestingwhetherthatnaptionoranynartionsoconceivedandsodedicatedcanlongendureWeareqmetonagreatbattlefiemldoftzhatwarWehavecometodedicpateaportionofthatfieldasafinalrestingplaceforthosewhoheregavetheirlivesthatthatnationmightliveItisaltogetherfangandproperthatweshoulddothisButinalargersensewecannotdedicatewecannotconsecratewecannothallowthisgroundThebravelmenlivinganddeadwhostruggledherehaveconsecrateditfaraboveourpoorponwertoaddordetractTgheworldadswfilllittlenotlenorlongrememberwhatwesayherebutitcanneverforgetwhattheydidhereItisforusthelivingrathertobededicatedheretotheulnfinishedworkwhichtheywhofoughtherehavethusfarsonoblyadvancedItisratherforustobeherededicatedtothegreattdafskremainingbeforeusthatfromthesehonoreddeadwetakeincreaseddevotiontothatcauseforwhichtheygavethelastpfullmeasureofdevotionthatweherehighlyresolvethatthesedeadshallnothavediedinvainthatthisnationunsderGodshallhaveanewbirthoffreedomandthatgovernmentofthepeoplebythepeopleforthepeopleshallnotperishfromtheearth",
11+
983
12+
]
13+
]);
14+
15+
for (const [s, expected] of TEST_CASES) {
16+
it(`returns ${expected} when called with ${s}`, () => {
17+
expect(longestPalindrome(s)).toBe(expected);
18+
});
19+
}
20+
});

Diff for: solutions/longestPalindrome.ts

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// 409. Longest Palindrome
2+
// https://leetcode.com/problems/longest-palindrome/
3+
export default function longestPalindrome(s: string): number {
4+
const oddChars = new Set<number>();
5+
let count = 0;
6+
7+
for (let i = 0; i < s.length; ++i) {
8+
const char = s.charCodeAt(i);
9+
10+
if (oddChars.has(char)) {
11+
oddChars.delete(char);
12+
13+
count += 2;
14+
} else {
15+
oddChars.add(char);
16+
}
17+
}
18+
19+
return count + (oddChars.size >= 1 ? 1 : 0);
20+
}

0 commit comments

Comments
 (0)