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 f7bcdd9

Browse filesBrowse files
authored
Create 2131. Longest Palindrome by Concatenating Two Letter Words (#804)
2 parents 3cee3ae + eee3a2c commit f7bcdd9
Copy full SHA for f7bcdd9

File tree

1 file changed

+44
-0
lines changed
Filter options

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.