zoukankan      html  css  js  c++  java
  • 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.

    解释:构成回文字符串,最好的情况就是所有出现双数的字母都排上,中间再加一个单着的

    方法一:哈希表
    class Solution {
        public int longestPalindrome(String s) {
            int count=0;
            int tip=0;
            HashMap<Character,Integer> map=new HashMap<Character,Integer>();
            for(char c:s.toCharArray()){
               if(map.containsKey(c)) {
                   int nums=map.get(c);
                   map.put(c,nums+1);
               }else{
                   map.put(c,1);
               }
            }
            
            for(char c:s.toCharArray()){
                if(map.containsKey(c)) {
                   int nums=map.get(c);
                   if(nums%2==1){
                       tip=1;
                   }
                    count+=nums/2;
                    map.remove(c);
               }
            }
            return count*2+tip;
        }
    }

    方法二:数组
    这种方法思路很简单,但是空间和时间消耗都很大。
    class Solution {
        public int longestPalindrome(String s) {
            int[] chr = new int[256];
            for(char c:s.toCharArray()){
                chr[c]++;
            }
            int p=0;
            for(int c:chr){
                p+=(c/2)*2;
            }
            if(p<s.length()){
                p++;
            }
            return p;
        }
    }
    苟有恒,何必三更眠五更起;最无益,莫过一日暴十日寒。
  • 相关阅读:
    Untiy数据包的输出、加载和卸载
    Line 7.10 : Syntax error
    给力的数学巧算法!
    Unity3d + NGUI 的多分辨率适配
    Linq小记
    (转)为C# Windows服务添加安装程序
    Javamail使用代码整理
    .NET后台访问其他站点代码整理
    (转)2009-05-25 22:12 Outlook2007选择发送帐号
    (转)C#与Outlook交互收发邮件
  • 原文地址:https://www.cnblogs.com/shaer/p/10847122.html
Copyright © 2011-2022 走看看