Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 2131. Longest Palindrome by Concatenating Two Letter Words

Rain Hu

2131. 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:

Example 2:

Example 3:

Constraints:


二、分析

三、解題

1. Hash Table

int longestPalindrome(vector<string>& words) {
    unordered_map<string, int> paired;
    unordered_set<string> twin;
    int cnt = 0;
    for (string& word : words) {
        if (word[0] == word[1]) {
            if (twin.count(word)) {
                twin.erase(word);
                cnt += 4;
            } else {
                twin.insert(word);
            }
        } else {
            string rev = {word[1], word[0]};
            if (paired.count(rev) && paired[rev] > 0) {
                paired[rev]--;
                cnt += 4;
            } else {
                paired[word]++;
            }
        }
    }
    return cnt + (!twin.empty() ? 2 : 0);
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 212. Word Search II
Next
[LeetCode] 433. Minimum Genetic Mutation