2022-11-03 Daily Challenge

Today I have done leetcode's November LeetCoding Challenge with cpp.

November LeetCoding Challenge 3

Description

Longest Palindrome by Concatenating Two Letter Words

You are given an array of strings words. Each element of words consists of two lowercase English letters.

Create the longest possible palindrome by selecting some elements from words and concatenating them in any order. Each element can be selected at most once.

Return the length of the longest palindrome that you can create. If it is impossible to create any palindrome, return 0.

A palindrome is a string that reads the same forward and backward.

 

Example 1:

Input: words = ["lc","cl","gg"]
Output: 6
Explanation: One longest palindrome is "lc" + "gg" + "cl" = "lcggcl", of length 6.
Note that "clgglc" is another longest palindrome that can be created.

Example 2:

Input: words = ["ab","ty","yt","lc","cl","ab"]
Output: 8
Explanation: One longest palindrome is "ty" + "lc" + "cl" + "yt" = "tylcclyt", of length 8.
Note that "lcyttycl" is another longest palindrome that can be created.

Example 3:

Input: words = ["cc","ll","xx"]
Output: 2
Explanation: One longest palindrome is "cc", of length 2.
Note that "ll" is another longest palindrome that can be created, and so is "xx".

 

Constraints:

  • 1 <= words.length <= 105
  • words[i].length == 2
  • words[i] consists of lowercase English letters.

Solution

auto speedup = [](){
  cin.tie(nullptr);
  cout.tie(nullptr);
  ios::sync_with_stdio(false);
  return 0;
}();
class Solution {
public:
  int longestPalindrome(vector<string>& words) {
    int count[26][26] = {};
    for(const auto &word : words) {
      count[word[0] - 'a'][word[1] - 'a'] += 1;
    }
    int answer = 0;
    for(int first = 0; first < 25; ++first) {
      for(int second = first + 1; second < 26; ++second) {
        if(count[first][second] && count[second][first]) {
          answer += min(count[first][second], count[second][first]) * 4;
        }
      }
    }
    bool hasMid = false;
    for(int i = 0; i < 26; ++i) {
      answer += (count[i][i] & (INT_MAX - 1)) * 2;
      hasMid |= count[i][i] & 1;
    }
    answer += hasMid * 2;
    return answer;
  }
};

// Accepted
// 120/120 cases passed (411 ms)
// Your runtime beats 90.95 % of cpp submissions
// Your memory usage beats 100.00 % of cpp submissions (166.9 MB)