LeetCode 409. Longest Palindrome

该博客讨论了一种解决方法,即通过计算给定字符串中每个字符的出现次数来确定能构建的最长回文串的长度。在Python中,创建了一个长度为128的数组来存储字符计数,然后遍历计数数组,双数出现的字符可以成对构造回文串,单数出现的字符最多只能贡献一个到回文串中。如果有奇数个字符出现,结果长度加1。此外,还提到了其他解法,如使用HashSet来跟踪字符,以便消除并形成回文串。
摘要由CSDN通过智能技术生成

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.

Example 1:

Input: s = "abccccdd"
Output: 7
Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.

Example 2:

Input: s = "a"
Output: 1
Explanation: The longest palindrome that can be built is "a", whose length is 1.

Constraints:

  • 1 <= s.length <= 2000
  • s consists of lowercase and/or uppercase English letters only.

看错题了,以为是字符串里的最长回文串长度,没想到是字符串里出现的字母能组成的最长回文串的长度……嗯……直接计算每个字母的出现次数,双数就凑一对,单数就能成双的成双,不能成双的留一个下来就好。很简单,只是这题字符串可能有大小写字母,于是就用了个长度128的数组,直接存对应的char就行。

class Solution {
    public int longestPalindrome(String s) {
        int[] count = new int[128];
        for (char c : s.toCharArray()) {
            count[c]++;
        }

        int result = 0;
        boolean hasOdd = false;
        for (int i : count) {
            if (i % 2 == 0) {
                result += i;
            } else {
                result += (i - 1);
                hasOdd = true;
            }
        }

        return hasOdd ? result + 1 : result;
    }
}

看了大家的解法还有人用hashset,如果set里有就remove掉凑一对,最后看看set里还剩没剩,有剩就再+1就行了。代码不写了,贴别人的:Loading...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值