LeetCode 409. Longest Palindrome (Java版; Easy)

welcome to my blog

LeetCode 409. Longest Palindrome (Java版; Easy)

题目描述
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.

Note:
Assume the length of given string will not exceed 1,010.

Example:

Input:
"abccccdd"

Output:
7

Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.
第一次做; 核心: 1)回文串中的字符要么出现偶数次, 要么出现奇数次, 而且最多有一个字符出现过奇数次, 所以统计s中各个字符出现的次数, 找出里面有多少对相同的字符, 再判断有没有出现过奇数次的字符, 见代码; 2) 为什么要统计有多少对相同的字符, 而不是直接使用字符的奇偶性? 看这个例子,ccc, 可以构成的回文串最长为3, 一对cc再加上一个c
class Solution {
    public int longestPalindrome(String s) {
        //input check
        if(s==null ||s.length()==0){
            return 0;
        }
        int n = s.length();
        //65:A    97:a
        int[] arr = new int[122-65+1];
        for(int i=0; i<n; i++){
            arr[s.charAt(i)-'A']++;
        }
        //even表示有多少对相同的元素; odd表示奇数个的元素出现过多少次
        int even=0, odd=0;
        for(int a : arr){
            even += a/2;
            if(a%2==1){
                odd++;
            }
        }
        return odd>0? even*2+1 : even*2;
    }
}
力扣优秀题解; 统计字符串中出现次数为奇数的字符个数, 用count表示, 如果count==0, 表示所有的字符均出现偶数次, 所以最大的回文串就是整个字符串, 如果count>0, 那么最大的回文串长度就是原始字符串长度减去count再加1, 为什么要加1? 因为回文串中最多有一个字符出现奇数次
public int longestPalindrome(String s) {
    // 找出可以构成最长回文串的长度
    int[] arr = new int[128];
    for(char c : s.toCharArray()) {
        arr[c]++;
    }
    int count = 0;
    for (int i : arr) {
        count += (i % 2);
    }
    return count == 0 ? s.length() : (s.length() - count + 1);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值