Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit ef07b06

Browse files
committed
Add solution #2131
1 parent d9cda33 commit ef07b06

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,764 LeetCode solutions in JavaScript
1+
# 1,765 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -1632,6 +1632,7 @@
16321632
2127|[Maximum Employees to Be Invited to a Meeting](./solutions/2127-maximum-employees-to-be-invited-to-a-meeting.js)|Hard|
16331633
2129|[Capitalize the Title](./solutions/2129-capitalize-the-title.js)|Easy|
16341634
2130|[Maximum Twin Sum of a Linked List](./solutions/2130-maximum-twin-sum-of-a-linked-list.js)|Medium|
1635+
2131|[Longest Palindrome by Concatenating Two Letter Words](./solutions/2131-longest-palindrome-by-concatenating-two-letter-words.js)|Medium|
16351636
2140|[Solving Questions With Brainpower](./solutions/2140-solving-questions-with-brainpower.js)|Medium|
16361637
2145|[Count the Hidden Sequences](./solutions/2145-count-the-hidden-sequences.js)|Medium|
16371638
2154|[Keep Multiplying Found Values by Two](./solutions/2154-keep-multiplying-found-values-by-two.js)|Easy|
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* 2131. Longest Palindrome by Concatenating Two Letter Words
3+
* https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/
4+
* Difficulty: Medium
5+
*
6+
* You are given an array of strings words. Each element of words consists of two lowercase
7+
* English letters.
8+
*
9+
* Create the longest possible palindrome by selecting some elements from words and concatenating
10+
* them in any order. Each element can be selected at most once.
11+
*
12+
* Return the length of the longest palindrome that you can create. If it is impossible to create
13+
* any palindrome, return 0.
14+
*
15+
* A palindrome is a string that reads the same forward and backward.
16+
*/
17+
18+
/**
19+
* @param {string[]} words
20+
* @return {number}
21+
*/
22+
var longestPalindrome = function(words) {
23+
const map = new Map();
24+
let length = 0;
25+
let hasCenter = false;
26+
27+
for (const word of words) {
28+
map.set(word, (map.get(word) || 0) + 1);
29+
}
30+
31+
for (const word of map.keys()) {
32+
const reverse = word[1] + word[0];
33+
34+
if (word === reverse) {
35+
const count = map.get(word);
36+
length += Math.floor(count / 2) * 4;
37+
if (count % 2 === 1) hasCenter = true;
38+
} else if (map.has(reverse)) {
39+
const pairs = Math.min(map.get(word), map.get(reverse));
40+
length += pairs * 4;
41+
map.set(word, 0);
42+
map.set(reverse, 0);
43+
}
44+
}
45+
46+
return hasCenter ? length + 2 : length;
47+
};

0 commit comments

Comments
 (0)