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.

翻译:给定一个由小写或大写字母组成的字符串,找到可以用这些字母构建的最长的回文长度。

这是区分大小写的,例如"Aa"在这里不被视为回文。

注意:
假设给定字符串的长度不能超过1,010。

例:

输入:
“abccccdd” 

输出:
7 

说明:
可以构建的最长的回文为“dccaccd”,长度为7。

思路:

第一次循环用HashMap来存s内不同字符和其数量和,第二次循环依次判断map中的value是否为2的倍数,若为2的倍数则length加其value,若不为则加value-1;并标记标志为1,因为有单个字符出现最后结果要加一。

public int longestPalindrome(String s) {
        char[] s2a = s.toCharArray();
        Map<Character,Integer> map = new HashMap<Character,Integer>();
        int length = 0,flag = 0;
        for(int i = 0; i<s2a.length;i++){
            if(map.containsKey(s2a[i])){
                int sum = map.get(s2a[i]);
                sum++;
                map.put(s2a[i],sum);
            }else{
                map.put(s2a[i],1);
            }
                
        }
        for(Integer value : map.values()){
            if(value % 2 == 0){
                length += value;
            }else if(value % 2 == 1){
                flag = 1;
                length += (value-1);
            }
        }
        return length+flag;
    }

答案思路:

使用HashSet,循环判断set中是否有当前字符,若有则删除该元素,count计数加1,若没有直接加入该元素。最后s内成对的元素个数为count*2,若map中还有剩余的元素,则长度还要加1。

public int longestPalindrome(String s) {
        if(s==null || s.length()==0) return 0;
        HashSet<Character> hs = new HashSet<Character>();
        int count = 0;
        for(int i=0; i<s.length(); i++){
            if(hs.contains(s.charAt(i))){
                hs.remove(s.charAt(i));
                count++;
            }else{
                hs.add(s.charAt(i));
            }
        }
        if(!hs.isEmpty()) return count*2+1;
        return count*2;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值