LeetCode 2131 Longest Palindrome by Concatenating Two Letter Words (hash)

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.

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.

题目链接:https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/

题目大意:给一些长度为2的word,从中选若干拼接,求最长能拼出的回文串长度

题目分析:hash一下,对长度2的word最后单独再扫一便,因为可以放在最中间

17ms,时间击败95.04%

class Solution {
    public int longestPalindrome(String[] words) {
        int[] mp = new int[1000];
        int ans = 0;
        for (String word : words) {
            int idx1 = word.charAt(0) - 'a';
            int idx2 = word.charAt(1) - 'a';
            if (idx1 != idx2) {
                mp[idx1 * 26 + idx2]++;
                if (mp[idx2 * 26 + idx1] > 0) {
                    ans += 4;
                    mp[idx1 * 26 + idx2]--;
                    mp[idx2 * 26 + idx1]--;
                }
            } else {
                mp[idx1 * 26 + idx2]++;
                if (mp[idx1 * 26 + idx2] > 1) {
                    mp[idx1 * 26 + idx2] -= 2;
                    ans += 4;
                }
            }
        }
        for (int i = 0; i < 26; i++) {
            if (mp[i * 26 + i] > 0) {
                ans += 2;
                break;
            }
        }
        return ans;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值