【LeetCode】17. Longest Palindrome·最长回文串

30 篇文章 0 订阅

​活动地址:CSDN21天学习挑战赛

题目描述

英文版描述

Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. Letters are case sensitive, for example, "Aa" is not considered a palindrome here.

英文版地址

https://leetcode.com/problems/longest-palindrome/

中文版描述

给定一个包含大写字母和小写字母的字符串 s ,返回 通过这些字母构造成的 最长的回文串 。 在构造过程中,请注意 区分大小写 。比如 "Aa" 不能当做一个回文字符串。

示例 1:

输入:s = "abccccdd"

输出:7

解释: 我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。

示例 2:

输入:s = "a"

输入:1

示例 3:

输入:s = "bb"

输入: 2

提示:

  • 1 <= s.length <= 2000

  • s 只能由小写和/或大写英文字母组成

中文版地址

https://leetcode.cn/problems/longest-palindrome/

解题思路

回文串只有中间的字符可以是单个的,其余的必须是双数,所以我们先遍历输入的字符串,将它存放在Map<字符,数目>中(由于区分大小写,不然可以借鉴之前的默认27个字母的数组减少空间复杂度)

解题方法

俺这版

class Solution {
 public int longestPalindrome(String s) {
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            if (map.containsKey(s.charAt(i))) {
                map.put(s.charAt(i), map.get(s.charAt(i))+1);
            } else {
                map.put(s.charAt(i), 1);
            }
        }
        int count = 0;
        int countDouble = 0;
        for (Map.Entry entry : map.entrySet()) {
            Integer value = (Integer) entry.getValue();
            if (value > 0) {
                if (value % 2 == 0) {
                    countDouble += (value / 2);
                } else {
                    count = 1;
                    countDouble += (value / 2);
                }
            }
        }
        return count + countDouble * 2;
    }
}

复杂度分析

  • 时间复杂度

遍历字符串(设字符串长度为n) n + 遍历哈希表n = 2n,O(2n)=O(n)

  • 空间复杂度

由于 ASCII 字符数量为128(区分大小写) ,哈希表最多使用128 + 计数 2 = 130,O(130)=O(1)

官方版

class Solution {
    public int longestPalindrome(String s) {
        int[] count = new int[128];
        int length = s.length();
        for (int i = 0; i < length; ++i) {
            char c = s.charAt(i);
            count[c]++;
        }

        int ans = 0;
        for (int v: count) {
            ans += v / 2 * 2;
            if (v % 2 == 1 && ans % 2 == 0) {
                ans++;
            }
        }
        return ans;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AQin1012

求小鱼干呢~~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值