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


    ​活动地址: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个字母的数组减少空间复杂度)

    解题方法

    俺这版

    1. class Solution {
    2. public int longestPalindrome(String s) {
    3. Map map = new HashMap<>();
    4. for (int i = 0; i < s.length(); i++) {
    5. if (map.containsKey(s.charAt(i))) {
    6. map.put(s.charAt(i), map.get(s.charAt(i))+1);
    7. } else {
    8. map.put(s.charAt(i), 1);
    9. }
    10. }
    11. int count = 0;
    12. int countDouble = 0;
    13. for (Map.Entry entry : map.entrySet()) {
    14. Integer value = (Integer) entry.getValue();
    15. if (value > 0) {
    16. if (value % 2 == 0) {
    17. countDouble += (value / 2);
    18. } else {
    19. count = 1;
    20. countDouble += (value / 2);
    21. }
    22. }
    23. }
    24. return count + countDouble * 2;
    25. }
    26. }

    复杂度分析

    • 时间复杂度

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

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

    官方版

    1. class Solution {
    2. public int longestPalindrome(String s) {
    3. int[] count = new int[128];
    4. int length = s.length();
    5. for (int i = 0; i < length; ++i) {
    6. char c = s.charAt(i);
    7. count[c]++;
    8. }
    9. int ans = 0;
    10. for (int v: count) {
    11. ans += v / 2 * 2;
    12. if (v % 2 == 1 && ans % 2 == 0) {
    13. ans++;
    14. }
    15. }
    16. return ans;
    17. }
    18. }

  • 相关阅读:
    Jquery 获取当前时间日期
    单元测试的重要性
    微信点餐小程序项目 --- 干饭人联盟(开源、免费)
    前缀和(区间和,子矩阵的和)
    先行进位加法器
    来分析两道小题
    GAN生成手写数字(TensorFlow,Mnist数据集)
    W2311294-万宾科技可燃气体监测仪怎么进行数据监测
    .Net大数据平台Microsoft.Spark环境构建 附可运行源码。
    猿创征文|【第5天】SQL快速入门-必会的常用函数(SQL 小虚竹)
  • 原文地址:https://blog.csdn.net/aqin1012/article/details/126345296