-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestPalindrome.cpp
More file actions
50 lines (49 loc) · 1.4 KB
/
longestPalindrome.cpp
File metadata and controls
50 lines (49 loc) · 1.4 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
46
47
48
49
50
class Solution {
public:
int longestPalindrome(vector<string>& words) {
int ans = 0;
unordered_map<string, int> cnt, cnt2;
string s(2, ' ');
for (auto &w: words) {
if (w[0] == w[1]) {
++cnt2[w];
continue;
}
s[0] = w[1];
s[1] = w[0];
if (cnt[s]) {
--cnt[s];
ans += 4;
}
else ++cnt[w];
}
bool flag = true;
for (auto &it: cnt2) {
if ((it.second & 1) && flag) {
--it.second;
flag = false;
ans += 2;
}
ans += (it.second >> 1) << 2;
}
return ans;
}
};
class Solution {
public:
int longestPalindrome(vector<string>& words) {
int cnt[26][26] = {};
for (auto &w: words)
++cnt[w[0] - 'a'][w[1] - 'a'];
int ans = 0, odd = 0; // 是否有一个出现奇数次的 AA
for (int i = 0; i < 26; ++i) {
int c = cnt[i][i]; // 相同字符
ans += c & ~1; // 等价于 c - c % 2
odd |= c & 1;
for (int j = i + 1; j < 26; ++j) {
ans += min(cnt[i][j], cnt[j][i]) << 1; // AB BA 取出现次数最小值
}
}
return (ans + odd) << 1; // 上面的循环统计的是字符串个数,最后再乘 2
}
};