aboutsummaryrefslogtreecommitdiff
path: root/longest_palindrome_concat.cpp
blob: 3a42e0a5c28f33f549cec0db26d85d1ff0839889 (plain)
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
#include "leetcode.h"

class Solution {
public:
  int longestPalindrome(vector<string> &words) {
    unordered_map<string, int> um;
    for (auto w : words)
      ++um[w];
    int ans = 0, center = 0, sz = 2;
    for (auto [w, cnt] : um) {
      auto reversed = string(rbegin(w), rend(w));
      if (w == reversed) {
        ans += 2 * (cnt / 2);
        center |= cnt % 2;
      } else {
        auto it = um.find(reversed);
        if (it != end(um))
          ans += min(cnt, it->second);
      }
    }
    return sz * ans + (center ? sz : 0);
  }
};

int main() {
  Solution obj;
  vector<string> words = {"lc", "cl", "gg"};
  cout << obj.longestPalindrome(words);
}