LeetCode409 Longest Palindrome

本文介绍了一种求解给定字符串中能组成最长回文串的方法。通过统计字符串中每个字符的出现次数,该算法能够高效地计算出最大回文长度。特别注意的是,这里的回文判定对大小写敏感。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.

This is case sensitive, for example “Aa” is not considered a palindrome here.
给一个字符串,判断其字符所能组成的回文的最大长度。

解法

依然是统计每个字符的出现次数,在根据不同的次数为结果加上不同的值。

public int longestPalindrome(String s) {
        if (s.length() == 0) return 0;
        if (s.length() == 1) return 1;
        int[] recordLow = new int[26];
        int[] recordUp = new int[26];
        int count = 0;
        boolean extra = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c - 'a' >= 0) recordLow[c - 'a']++;
            else recordUp[c - 'A']++;
        }

        for (int i = 0; i < 26; i++) {

            if (recordLow[i] % 2 == 0)
                count += recordLow[i] / 2;
            else {
                count += (recordLow[i] - 1) / 2;
                extra = true;
            }

            if (recordUp[i] % 2 == 0)
                count += recordUp[i] / 2;
            else {
                count += (recordUp[i] - 1) / 2;
                extra = true;
            }
        }

        if (extra) return count * 2 + 1;
        else return count * 2;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值