资讯专栏INFORMATION COLUMN

[LintCode] Longest Palindrome

nicercode / 2471人阅读

Problem

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.

Notice

Assume the length of given string will not exceed 1010.

Example

Given s = "abccccdd" return 7

One longest palindrome that can be built is "dccaccd", whose length is 7.

Solution
public class Solution {
    /*
     * @param s: a string which consists of lowercase or uppercase letters
     * @return: the length of the longest palindromes that can be built
     */
    public int longestPalindrome(String s) {
        // write your code here
        int res = 0;
        //Use HashMap to store occurrence, when it"s even, res adds 2 and map deletes the key
        Map map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (map.containsKey(ch)) {
                map.remove(ch);
                res += 2;
            } else {
                map.put(ch, 1);
            }
        }
        if (res < s.length()) res += 1;
        return res;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/68259.html

相关文章

  • [LintCode/LeetCode] Longest Palindrome Substring

    摘要:是左闭右开区间,所以要。,要理解是和之间只有一个元素。循环每次的时候,都要更新子串更大的情况。补一种中点延展的方法循环字符串的每个字符,以该字符为中心,若两边为回文,则向两边继续延展。循环返回长度最长的回文串即可。 Problem Given a string S, find the longest palindromic substring in S. You may assume ...

    AaronYuan 评论0 收藏0
  • [Leetcode]Longest Palindrome

    摘要:解题思路我们发现结果其实就是字符的偶数个数是否有单一的字符,如果有就加把单一字符放在回文中间,如果没有就加字母区分大小写,代码 Longest PalindromeGiven a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that...

    beita 评论0 收藏0
  • leetcode409.Longest Palindrome

    摘要:题目要求输入一个字符串,计算用这个字符串中的值构成一个最长回数的长度是多少。直观来看,我们立刻就能想到统计字符串中每个字符出现的次数,如果该字符出现次数为偶数,则字符一定存在于回数中。这个细节需要注意。 题目要求 Given a string which consists of lowercase or uppercase letters, find the length of the...

    linkin 评论0 收藏0
  • [LeetCode/LintCode] Largest Palindrome Product

    Problem Find the largest palindrome made from the product of two n-digit numbers. Since the result could be very large, you should return the largest palindrome mod 1337. Example Input: 2Output: 987Ex...

    Barry_Ng 评论0 收藏0
  • [LeetCode/LintCode] Valid Palindrome

    Valid Palindrome Problem Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Example A man, a plan, a canal: Panama is a palindrome. race a ca...

    Ververica 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<