Leetcode 5962:连接两字母单词得到的最长回文串

题目描述

给你一个字符串数组 words 。words 中每个元素都是一个包含 两个 小写英文字母的单词。

请你从 words 中选择一些元素并按 任意顺序 连接它们,并得到一个 尽可能长的回文串 。每个元素 至多 只能使用一次。

请你返回你能得到的最长回文串的 长度 。如果没办法得到任何一个回文串,请你返回 0 。

回文串 指的是从前往后和从后往前读一样的字符串。

示例 1:

输入:words = ["lc","cl","gg"]
输出:6
解释:一个最长的回文串为 "lc" + "gg" + "cl" = "lcggcl" ,长度为 6 。
"clgglc" 是另一个可以得到的最长回文串。
示例 2:

输入:words = ["ab","ty","yt","lc","cl","ab"]
输出:8
解释:最长回文串是 "ty" + "lc" + "cl" + "yt" = "tylcclyt" ,长度为 8 。
"lcyttycl" 是另一个可以得到的最长回文串。
示例 3:

输入:words = ["cc","ll","xx"]
输出:2
解释:最长回文串是 "cc" ,长度为 2 。
"ll" 是另一个可以得到的最长回文串。"xx" 也是。
 

提示:

1 <= words.length <= 105
words[i].length == 2
words[i] 仅包含小写英文字母。


来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-palindrome-by-concatenating-two-letter-words
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

class Solution {
public:
    int longestPalindrome(vector<string>& words) {
        int ans = 0;
        unordered_map<string, int> mp;
        unordered_set<string> st;
        for(auto &word : words) {
            mp[word]++;
            st.insert(word);
        }
        bool flag = false;
        for(auto &it : st) {
            if(it[0] == it[1]) {
                int a = mp[it];
                if(a % 2 == 0) ans += a;
                else {
                    ans += a-1;
                    if(!flag) {
                        ans++;
                        flag = true;
                    }
                }
            } else {
                int a = mp[it];
                string tmp = it;
                reverse(tmp.begin(), tmp.end());
                int b = mp[tmp];
                ans += min(a, b);
            }
        }
        return ans*2;
    }
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值