Leetcode 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. 

解法1:先直接把字符数v加到length上,再判断v的奇偶性,如果偶数就不用管了,如果是奇数就减个1,同时标记一下values中有奇数.因为前面的奇数的情况,我们每次都只加偶数个(即是v-1个),所以在最后我们要做一下处理.我的做法是,如果我们的字符数集合中有奇数(即hasOdd为true),我就让结果+1,这个意思就是取任意一个奇数个字符的字符放在回文字符串的中间位置.这个是我自己的解法,感觉思路不是那么清晰.看了别人的解法,感觉很清晰,见解法2

public int longestPalindrome(String s) {
        HashMap<Character, Integer> palindromeMap = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            palindromeMap.put(ch, palindromeMap.getOrDefault(ch, 0)+1);
        }
        Collection<Integer> values = palindromeMap.values();
        int length = 0; boolean hasOdd = false;
        for (int v : values) {
            length += v;
            if (v%2 == 1) {
                hasOdd = true;
                length -= 1;
            }
        }
        return hasOdd? length+1 : length;
    }

解法2:分类讨论,对回文字符长度的奇偶性做讨论.不论某个字符的个数是奇数个还是偶数个,都只取偶数个.如果当前回文字符串长度为偶数个,同时某个字符的个数为奇数个,则将该字符放回文串的中间,对length做+1的操作.

public static int longestPalindrome(String s) {
        HashMap<Character, Integer> palindromeMap = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            palindromeMap.put(ch, palindromeMap.getOrDefault(ch, 0)+1);
        }
        Collection<Integer> values = palindromeMap.values();
        int length = 0;
        for (int v : values) {
            length += v/2*2;
            if (length%2 == 0 && v%2 == 1) length ++;
        }
        return length;
    }

 https://leetcode.com/problems/longest-palindrome/ 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值