-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
45 lines (43 loc) · 1.17 KB
/
Solution.cs
File metadata and controls
45 lines (43 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class Solution
{
public int LongestPalindrome(string[] words)
{
Dictionary<string, int> count = [];
foreach (string word in words)
{
count[word] = count.GetValueOrDefault(word, 0) + 1;
}
int ret = 0;
bool extra = false;
HashSet<string> visited = [];
foreach (var pair in count)
{
string key1 = pair.Key;
string key2 = Reverse(pair.Key);
if (!visited.Add(key1)) continue;
visited.Add(key2);
int count1 = count.GetValueOrDefault(key1, 0);
int count2 = count.GetValueOrDefault(key2, 0);
if (key1 == key2)
{
ret += 4 * (Math.Min(count1, count2) / 2);
if (count1 % 2 == 1)
{
extra = true;
}
}
else
{
ret += 4 * Math.Min(count1, count2);
}
}
if (extra) ret += 2;
return ret;
}
string Reverse(string s)
{
char[] charArr = s.ToCharArray();
Array.Reverse(charArr);
return new string(charArr);
}
}