Leetcode 409. Longest Palindrome

public class Solution {
    public int longestPalindrome(String s) {
        int len = 0;
        // an integer array to save the frequency of the letters in s
        int[] hash = new int[128];
        
        // count the frequency
        for (char c : s.toCharArray())
            hash[c]++;
        
        // scan the frequency array, add all even numbers and odd numbers minus 1 to len
        for (int feq : hash) {
            if (feq == 0) continue;
            if (feq % 2 == 0)   
                len += feq;
            else 
            	len += feq-1;
        }
        
        // if not all feqs are even, put last odd frequency letter in the middle so we need to add 1 to len
        // if all feqs are even that is len = s.length() just return len
        return (len == s.length()) ? len : len + 1;
    }
}

HashSet solution.

public class Solution {
    public int longestPalindrome(String s) {
        HashSet<Character> hs = new HashSet<Character>();
        int pairs = 0;
        for (char c : s.toCharArray()) {
            if (!hs.add(c)) {
                hs.remove(c);
                pairs++;
            }
        }
        return (hs.isEmpty()) ? 2*pairs : 2*pairs+1;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值