Skip to content

Instantly share code, notes, and snippets.

@dluciano
Created November 3, 2022 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dluciano/b0452572bf996ce72ae65bc8a9df6b8b to your computer and use it in GitHub Desktop.
Save dluciano/b0452572bf996ce72ae65bc8a9df6b8b to your computer and use it in GitHub Desktop.
2131. Longest Palindrome by Concatenating Two Letter Words
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