409. Longest Palindrome

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.
思路:

编译好几次不过,注意几个问题,最大奇数字母长度全部加进去,其他奇数字母加上偶数部分。

		int upperNum[] = new int[26];
		int lowerNum[] = new int[26];
		for (int i = 0; i < s.length(); i++) {
			if (s.charAt(i) - 'a' >= 0) {
				lowerNum[s.charAt(i) - 'a']++;
			} else {
				upperNum[s.charAt(i) - 'A']++;
			}
		}
		int maxSingle = 0;
		int len = 0;
		for (int i = 0; i < lowerNum.length; i++) {
			if (lowerNum[i] == 0)
				continue;
			if (lowerNum[i] % 2 == 0) {
				len += lowerNum[i];
			} else {
				if (lowerNum[i] > maxSingle) {
					len += maxSingle - 1;
					maxSingle = lowerNum[i];
				} else
					len += lowerNum[i] - 1;
			}
		}
		for (int i = 0; i < upperNum.length; i++) {
			if (upperNum[i] == 0)
				continue;
			if (upperNum[i] % 2 == 0) {
				len += upperNum[i];
			} else {
				if (upperNum[i] > maxSingle) {
					len += maxSingle - 1;
					maxSingle = upperNum[i];
				} else
					len += upperNum[i] - 1;
			}
		}
		return (maxSingle == 0) ? len : len + maxSingle + 1;

Set:

public class Solution {  
    public int longestPalindrome(String s) {  
        Set<Character> set = new HashSet<>();  
        int count = 0;  
        for (char c : s.toCharArray()) {  
            if (set.contains(c)) {  
                set.remove(c);  
                count += 2;  
            } else {  
                set.add(c);  
            }  
        }  
        return count + (set.size() > 0 ? 1 : 0);  
    }  
}  




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值