Longest Palindrome

题目地址:https://leetcode.com/problems/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.

题目要求找到已知字符串能够拼出的最长回文字符串的长度。

首先对该字符串中各个字符出现的次数做个统计,出现两次以上的字符都可以用来拼接回文字符串。如果有出现奇数次的字符,那么它就作为回文字符串的中间字符。

public class LongestPalindrome {
    public int longestPalindrome(String s) {
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();

        for (int i = 0; i < s.length(); i++) {
            if (!map.containsKey(s.charAt(i))) {
                map.put(s.charAt(i), 1);
            } else {
                map.put(s.charAt(i), map.get(s.charAt(i)) + 1);
            }
        }

        System.out.println(map);

        int len = 0;
        boolean isOdd = false;

        for (Map.Entry e: map.entrySet()) {
            if ((int)e.getValue() % 2 == 1 )
                isOdd = true;
            len += ((int)e.getValue() / 2) * 2;
        }
        if (isOdd)
            len++;

        return len;
    }

    public static void main(String[] args) {
        LongestPalindrome longestPalindrome = new LongestPalindrome();
        System.out.println(longestPalindrome.longestPalindrome("abccccdd"));
    }
}

以上实现效率稍稍差了些,因为首先花了O(n)的时间遍历了一次字符串,然后又遍历了一次map,map的大小是由字符串中字符的重复程度决定的,最差情况也就是字符串中没有重复字符,那么遍历map的时间复杂度也是O(n)。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值