File tree 2 files changed +49
-1
lines changed 2 files changed +49
-1
lines changed Original file line number Diff line number Diff line change 1
- # 1,764 LeetCode solutions in JavaScript
1
+ # 1,765 LeetCode solutions in JavaScript
2
2
3
3
[ https://leetcodejavascript.com ] ( https://leetcodejavascript.com )
4
4
1632
1632
2127|[ Maximum Employees to Be Invited to a Meeting] ( ./solutions/2127-maximum-employees-to-be-invited-to-a-meeting.js ) |Hard|
1633
1633
2129|[ Capitalize the Title] ( ./solutions/2129-capitalize-the-title.js ) |Easy|
1634
1634
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|
1635
1636
2140|[ Solving Questions With Brainpower] ( ./solutions/2140-solving-questions-with-brainpower.js ) |Medium|
1636
1637
2145|[ Count the Hidden Sequences] ( ./solutions/2145-count-the-hidden-sequences.js ) |Medium|
1637
1638
2154|[ Keep Multiplying Found Values by Two] ( ./solutions/2154-keep-multiplying-found-values-by-two.js ) |Easy|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments