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.
给定一个字符串包含大小写,用字符串中的字符组成一个回文串求符合要求的回文串的最大长度,

思路:统计字符串中每个字符出现的次数 再进行处理

刚开始错误:遍历字符串中字符出现的次数,偶数次的直接加进去,奇数次的加最大的。  奇数次的可以去掉一个变成偶数次然后加进去,如 aaaba可以变成abba


因为区分大小写所以建一个数组包含ascII A-z的范围,58个字符,不用担心Z-a之间的6个字符因为它们不会出现统计次数是为0 直接加到len中也不会影响结果

在处理的时候需要考虑奇数的问题,如果是奇数比较它和之前出现的最大奇数次作比较如果大于max则让原来的max-1 加到len中类似aaabb中的a,把这个变成max,否则将这个数-1加到len中,最后返回的时候需要判断 max是否==0 ,如果等于说明字符串中的字符都是出现了偶数次,返回len,如果max!=0 则说明出现了不止一个奇数次,因为在第一次处理max的时候加了一个max-1 是-1 把这个corner去去掉 返回 len+max+1就可以了


run time:11ms

public class Solution {
    public int longestPalindrome(String s) {
        int []cnt=new int[58];
        int max=0;
        int len=0;
        for(int i=0;i<s.length();i++){
            cnt[s.charAt(i)-'A']++;
        }
        for(int i=0;i<58;i++){
            if(cnt[i]%2==0)
                len+=cnt[i];
            else {
                if(cnt[i]>max){
                    len+=max-1;
                    max=cnt[i];
                }
                else len=len+cnt[i]-1;
            }
        }
        return max==0?len:len+max+1;
    }
}


discuss中还有一种解法就是讲出现过的字符都放到hashset中,如果再次碰到则将这个字符remove,len+2,最终的记过就是如果字符出现偶数次则最后在hashset中不存在,如果出现奇数次最后会出现在hashset中,同时每出现两次时已经加到len中,不需要考虑太多其他情况

runtime:18ms


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);
    }
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值