Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit eee3a2c

Browse filesBrowse files
authored
Create 2131. Longest Palindrome by Concatenating Two Letter Words
1 parent 3cee3ae commit eee3a2c
Copy full SHA for eee3a2c

File tree

Expand file treeCollapse file tree

1 file changed

+44
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+44
-0
lines changed
+44Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class Solution {
2+
public:
3+
int longestPalindrome(vector<string>& words)
4+
{
5+
unordered_map<string, int> count;
6+
unordered_set<string> visited, store;
7+
for(auto &s : words)
8+
{
9+
count[s] += 1;
10+
store.insert(s);
11+
}
12+
13+
int ans = 0, flag = true;
14+
for(auto &s : store)
15+
{
16+
int cnt = count[s];
17+
if(visited.count(s)) continue;
18+
if(s[0] == s[1])
19+
{
20+
if(cnt % 2)
21+
{
22+
cnt -= 1;
23+
if(flag)
24+
{
25+
ans += 2;
26+
flag = false;
27+
}
28+
}
29+
ans += cnt * 2;
30+
continue;
31+
}
32+
33+
string ss = string{ s[1], s[0] };
34+
35+
int cnt2 = count[ss];
36+
int maxAdd = min(cnt, cnt2);
37+
ans += (maxAdd * 2) * 2;
38+
39+
visited.insert(s);
40+
visited.insert(ss);
41+
}
42+
return ans;
43+
}
44+
};

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.