Skip to content

Commit 2fdee3e

Browse files
add 2131 alt sol
1 parent 36ecd96 commit 2fdee3e

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

contest/src/main/java/com/github/contest/Execute.kt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package com.github.contest
22

33

4-
import com.github.contest.hashTable.longestPalindrome
4+
import com.github.contest.hashTable.longestPalindromeAlternativeSolution
55
import com.github.contest.math.numberOfPowerfulInt
66
import com.github.contest.slidingWindow.customStructure.rabinKarpMultiPattern
77
import com.github.contest.slidingWindow.customStructure.slidingWindowClassic
@@ -17,7 +17,7 @@ import java.util.TreeMap
1717
fun main() {
1818

1919
val arr = arrayOf("em", "pe", "mp", "ee", "pp", "me", "ep", "em", "em", "me")
20-
longestPalindrome(
20+
longestPalindromeAlternativeSolution(
2121
arr
2222
).also { println(it) }
2323
}

contest/src/main/java/com/github/contest/hashTable/HashTableAlternativeSolution.kt

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,4 +114,32 @@ fun findEvenNumbersAlternativeSolution(digits: IntArray): IntArray {
114114
}
115115

116116
return result.sorted().toIntArray()
117-
}
117+
}
118+
119+
/**
120+
* 2131. Longest Palindrome by Concatenating Two Letter Words
121+
*/
122+
123+
fun longestPalindromeAlternativeSolution(words: Array<String>): Int {
124+
val freq = words.groupingBy { it }.eachCount().toMutableMap()
125+
var len = 0
126+
var centralPair = 0
127+
128+
for ((word, count) in freq) {
129+
if (word[0] == word[1]) {
130+
if (count % 2 == 0) {
131+
len += (count * 2)
132+
} else {
133+
len += (count - 1) * 2
134+
centralPair = 2
135+
}
136+
} else {
137+
val mirror = "${word[1]}${word[0]}"
138+
val minPairs = minOf(count, freq.getOrDefault(mirror, 0))
139+
len += (minPairs * 4)
140+
freq[word] = 0
141+
}
142+
}
143+
144+
return len + centralPair
145+
}

0 commit comments

Comments
 (0)