leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

2131.cpp (716B)


      1 class Solution {
      2   public:
      3     int longestPalindrome(vector<string> &words) {
      4         unordered_map<string, int> um;
      5         for (string &w : words)
      6             um[w]++;
      7 
      8         bool odd = false;
      9         int res = 0;
     10         for (const auto &[s, count] : um) {
     11             if (!count) continue;
     12 
     13             if (s[0] == s[1]) {
     14                 if (count % 2 == 0) {
     15                     res += count;
     16                 } else {
     17                     res += count - 1;
     18                     odd = true;
     19                 }
     20             } else if (s[0] < s[1] && um.count({s[1], s[0]})) {
     21                 res += min(count, um[{s[1], s[0]}]) * 2;
     22             }
     23         }
     24         if (odd) res++;
     25         return res * 2;
     26     }
     27 };