Skip to content

Commit 3414b34

Browse files
committed
added longestPalindrome easy leetcode solution
1 parent 72cc4a1 commit 3414b34

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Easy/longestPalindrome.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Given a string which consists of lowercase or uppercase letters,
2+
// find the length of the longest palindromes that can be built with those letters.
3+
// This is case sensitive, for example "Aa" is not considered a palindrome here.
4+
5+
// Note:
6+
// Assume the length of given string will not exceed 1,010.
7+
// Example:
8+
// Input:
9+
// "abccccdd"
10+
// Output:
11+
// 7
12+
13+
// Explanation:
14+
// One longest palindrome that can be built is "dccaccd", whose length is 7.
15+
16+
const test1 = "abccccdd";
17+
18+
const longestPalindrome = (str) => {
19+
if (!str.length) return 0;
20+
if (str.length === 1) return 1;
21+
let longestCount = 0;
22+
const strMap = {};
23+
for (const char of str) {
24+
if (strMap[char]) {
25+
strMap[char]++;
26+
} else {
27+
strMap[char] = 1;
28+
}
29+
}
30+
for (const key in strMap) {
31+
longestCount += Math.floor(strMap[key] / 2) * 2;
32+
if (longestCount % 2 === 0 && strMap[key] % 2 === 1) {
33+
longestCount++;
34+
}
35+
}
36+
return longestCount;
37+
}
38+
39+
console.log(longestPalindrome(test1)); // 7
40+
// console.log(longestPalindrome(test2)); // 7

0 commit comments

Comments
 (0)