409. Longest Palindrome

本文探讨了如何从给定的字符串中构建最长的回文串,通过对字符频率的统计,巧妙处理奇数次字符,实现高效算法。提供两种解决方案,一种为详细步骤解析,另一种为简洁的leetcode标准解法。

题目

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.

我的想法

遍历字符串,对字符频率进行统计,所有的偶数都可以直接count。奇数次字符需要注意(这个bug找了好久!):每个字符不是一个整体,假设a出现了5次,我可以只count 4!。这意味着所有的奇数次字符在count的时候需要-1。而在函数返回时需要注意(这里第一次也写错了!!):如果有>=3的奇数次字符需要在最后返回时+1,以构成奇数型回文串...aba...。如果没有,比如...aa...,不要+1!!!!

class Solution {
    public int longestPalindrome(String s) {
        if(s == null || s.length() == 0) return 0;

        Map<Character, Integer> map = new HashMap<>();
        int res = 0;
        for(int i = 0; i < s.length(); i++) {
            Integer count = map.get(s.charAt(i));
            if(count != null) {
                map.put(s.charAt(i), ++count);
            }
            else {
                map.put(s.charAt(i), 1);
            }
        }
        ArrayList<Integer> list = new ArrayList<>(map.values());
        boolean oddCenter = false;
        for(int i = 0; i < list.size(); i++){
            int count = list.get(i);
            if(count % 2 == 1) oddCenter = true;
            res += (count % 2 == 0) ? count : count - 1;
        }
        return oddCenter ? res + 1 : res;
    }
}

解答

leetcode solution: Greedy
写法很简洁,因为a-Z本身只有128,可以直接用数组来操作。利用v / 2 * 2先取整再乘二,避免我写的那种冗余判断。但其实没有太明白这个为什么算贪心。

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

        int ans = 0;
        for (int v: count) {
            ans += v / 2 * 2;
            //判断是否有unique center
            if (ans % 2 == 0 && v % 2 == 1)
                ans++;
        }
        return ans;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值