Created
November 3, 2022 15:36
-
-
Save dluciano/b0452572bf996ce72ae65bc8a9df6b8b to your computer and use it in GitHub Desktop.
2131. Longest Palindrome by Concatenating Two Letter Words
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public int LongestPalindrome(string[] words) { | |
var freq = new Dictionary<string, int>(); | |
var palindromes = new HashSet<string>(); | |
var counter = 0; | |
foreach(var word in words){ | |
if(!freq.ContainsKey(word)) | |
freq[word] = 0; | |
freq[word]++; | |
if(word[0] == word[1]) | |
_ = palindromes.Add(word); | |
} | |
foreach(var palindrome in palindromes){ | |
if(freq[palindrome] == 1) | |
continue; | |
if(freq[palindrome] % 2 == 0){ | |
counter += 2 * freq[palindrome]; | |
freq.Remove(palindrome); | |
} | |
else { | |
counter += 2 * (freq[palindrome] - 1); | |
freq[palindrome] = 1; | |
} | |
} | |
foreach(var kv in freq){ | |
if(kv.Key[0] == kv.Key[1]){ | |
counter += 2; | |
break; | |
} | |
} | |
foreach(var palindrome in palindromes) | |
if(freq.ContainsKey(palindrome)) | |
freq.Remove(palindrome); | |
foreach(var word in words){ | |
var reversed = $"{word[1]}{word[0]}"; | |
if(freq.ContainsKey(word) && freq.ContainsKey(reversed)){ | |
var min = Math.Min(freq[word], freq[reversed]); | |
counter += min * 4; | |
freq.Remove(word); | |
freq.Remove(reversed); | |
} | |
} | |
return counter; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment